Two types of exceptions are defined in Java
- Checked exceptions:checked exceptions inherits from the exception class, calling client code that throws this exception API must handle the lead, otherwise it cannot be compiled, The exception is either caught by a catch clause or continues to be thrown through the throws clause. such as: SQLException
- Unchecked Exceptions:runtimeexception is also inherited from the exception class, however all exceptions inherited from RuntimeException are treated specially, and this type exception must be handled without requiring the client to call. such as: NullPointerException, arrayindexoutofboundexception
Checked exceptions
Exceptiontester class
package cn.sehzh;public class ExceptionTester { public void testException() throws Exception { throw new Exception("异常"); }}
Main class
package cn.sehzh;public class Main { public static void main(String[] args) { ExceptionTester exceptionTester = new ExceptionTester(); try { //客户端调用时必须捕获或抛出,这里采用捕获 exceptionTester.testException(); } catch (Exception e) { e.printStackTrace(); } }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
Unchecked exceptions
Exceptiontester class
package cn.sehzh;public class ExceptionTester { public void testException(){ throw new RuntimeException("运行时异常"); }}
Main class
package cn.sehzh;public class Main { public static void main(String[] args) { ExceptionTester exceptionTester = new ExceptionTester(); //这里没有要求客户端调用时必须处理 exceptionTester.testException(); }}
Two exceptions in Java (Checked exceptions and unchecked exceptions)