1. Introduction
try…catch…finally is probably a familiar statement to everyone, and it seems to be very simple to use and logically easy to understand. However, the "lessons" I have personally experienced tell me that this thing is not as simple and obedient as I imagined. Do not believe? Then take a look at the following code and "guess" what the result will be after it is executed? Do not look back at the answers, and you are not allowed to execute the code to see the real answers. If your answer is correct, then you don’t need to waste time reading this article.
package Test; public class TestException { public TestException() { } boolean testEx() throws Exception { boolean ret = true; try { ret = testEx1(); } catch (Exception e) { System.out.println("testEx, catch exception"); ret = false; throw e; } finally { System.out.println("testEx, finally; return value=" + ret); return ret; } } boolean testEx1() throws Exception { boolean ret = true; try { ret = testEx2(); if (!ret) { return false; } System.out.println("testEx1, at the end of try"); return ret; } catch (Exception e) { System.out.println("testEx1, catch exception"); ret = false; throw e; } finally { System.out.println("testEx1, finally; return value=" + ret); return ret; } } boolean testEx2() throws Exception { boolean ret = true; try { int b = 12; int c; for (int i = 2; i >= -2; i--) { c = b / i; System.out.println("i=" + i); } return true; } catch (Exception e) { System.out.println("testEx2, catch exception"); ret = false; throw e; } finally { System.out.println("testEx2, finally; return value=" + ret); return ret; } } public static void main(String[] args) { TestException testException1 = new TestException(); try { testException1.testEx(); } catch (Exception e) { e.printStackTrace(); } } }
What’s your answer? Is it the answer below? return value=false
false
If your answer is really as stated above, then you are wrong. ^_^, then I suggest you read this article carefully or use the above code to modify, execute, and test it in various situations. You will find that many things are not as simple as you originally imagined. Now announce the correct answer:
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
The finally statement block should not appear and return should appear. The return ret above is best used in other statements to handle related logic.
2. JAVA exception
Exception refers to various unexpected situations, such as: file not found, network connection failure, illegal parameters, etc. An exception is an event that occurs during program execution and interferes with the normal flow of instructions. Java describes various exceptions through numerous subclasses of the Throwable class in the API. Thus, Java exceptions are objects, instances of a Throwable subclass, that describe error conditions that occur in a piece of coding. Error will throw an exception when the condition is generated.
Java exception class hierarchy diagram:
In Java, all exceptions have a common ancestor Throwable (throwable). Throwable specifies the commonality of any problem in code that can be propagated through a Java application using an exception propagation mechanism. Throwable: There are two important subclasses: Exception (Exception) and Error (Error). Both are important subclasses of Java exception handling, and each contains a large number of subclasses. Error: It is an error that the program cannot handle, indicating a serious problem in running the application. Most errors have nothing to do with actions performed by the code writer and instead represent problems with the JVM (Java Virtual Machine) while the code is running. For example, Java virtual machine running error (Virtual MachineError), when the JVM no longer has the memory resources required to continue executing the operation, an OutOfMemoryError will occur. When these exceptions occur, the Java Virtual Machine (JVM) generally chooses to terminate the thread.These errors indicate that the fault occurs in the virtual machine itself, or occurs when the virtual machine attempts to execute an application, such as Java virtual machine running error (Virtual MachineError), class definition error (NoClassDefFoundError), etc. These errors are uncheckable because they are outside the control and processing capabilities of the application program, and most of them are conditions that are not allowed to occur when the program is running. For a well-designed application, even if an error does occur, there should be no attempt to handle the exception it caused. In Java, errors are described through subclasses of Error.
Exception: It is an exception that the program itself can handle.
Exception class has an important subclass RuntimeException. The RuntimeException class and its subclasses represent errors caused by "common JVM operations." For example, if you try to use a null object reference, divide by zero, or the array is out of bounds, runtime exceptions (NullPointerException, ArithmeticException) and ArrayIndexOutOfBoundException are thrown respectively.
Note: The difference between exceptions and errors: Exceptions can be handled by the program itself, but errors cannot be handled.
Usually, Java exceptions (including Exception and Error) are divided into checkable exceptions (checked exceptions) and unchecked exceptions (unchecked exceptions).
Checkable exceptions (exceptions that the compiler requires to be handled): Exceptions that are easy to occur and are tolerable when a correct program is running. Although checkable exceptions are abnormal situations, their occurrence can be expected to a certain extent, and once such abnormal situations occur, they must be handled in some way.
Except for RuntimeException and its subclasses, other Exception classes and their subclasses are checkable exceptions. The characteristic of this kind of exception is that the Java compiler will check it. That is to say, when this kind of exception may occur in the program, either use a try-catch statement to catch it, or use a throws clause to declare it, otherwise the compilation will not pass. .
Uncheckable exceptions (exceptions that the compiler does not require forced handling): include runtime exceptions (RuntimeException and its subclasses) and errors (Error).
Exception This kind of exception is divided into two major categories: runtime exceptions and non-runtime exceptions (compilation exceptions). The program should handle these exceptions as much as possible.
Runtime exceptions: They are all exceptions of the RuntimeException class and its subclasses, such as NullPointerException (null pointer exception), IndexOutOfBoundsException (subscript out-of-bounds exception), etc. These exceptions are not checked exceptions. You can choose to capture them in the program, or not deal with. These exceptions are generally caused by program logic errors, and the program should try to avoid the occurrence of such exceptions from a logical perspective.
The characteristic of runtime exceptions is that the Java compiler will not check it. That is to say, when this type of exception may occur in the program, even if it is not captured with a try-catch statement, it is not declared to be thrown with a throws clause. It will also compile and pass.
Non-runtime exceptions (compilation exceptions): Exceptions other than RuntimeException, they all belong to the Exception class and its subclasses. From the perspective of program syntax, it is an exception that must be handled. If it is not handled, the program will not be compiled. Such as IOException, SQLException, etc. and user-defined Exceptions. Generally, no custom checked exceptions are required.
3. Exception handling mechanism
In Java applications, the exception handling mechanism is: throwing exceptions and catching exceptions.
Throwing an exception: When an error occurs in a method and an exception is thrown, the method creates an exception object and delivers it to the runtime system. The exception object contains exception information such as the exception type and the program status when the exception occurs. The runtime system is responsible for finding the code to handle the exception and executing it.
Catching exceptions: After a method throws an exception, the runtime system will turn to find a suitable exception handler. A potential exception handler is a collection of methods that remain in the call stack in sequence when an exception occurs. When the exception type that the exception handler can handle matches the exception type thrown by the method, it is a suitable exception handler. The runtime system starts from the method where the exception occurred and checks back the methods in the call stack until it finds the method containing the appropriate exception handler and executes it. When the runtime system traverses the call stack and does not find a suitable exception handler, the runtime system terminates. At the same time, it means the termination of the Java program.
For runtime exceptions, errors or checkable exceptions, the exception handling methods required by Java technology are different.
Due to the uncheckable nature of runtime exceptions, in order to implement applications more reasonably and easily, Java stipulates that runtime exceptions will be automatically thrown by the Java runtime system, allowing applications to ignore runtime exceptions.
For errors that may occur during method running, when the running method does not want to catch it, Java allows the method to not make any throwing statement. Because most Error exceptions are situations that should never be allowed to occur and are exceptions that reasonable applications should not catch.
For all checkable exceptions, Java stipulates that a method must catch it, or declare it to be thrown outside the method. That is, when a method chooses not to catch checkable exceptions, it must declare that it will throw an exception.
Methods that can catch exceptions need to provide exception handlers of corresponding types. The captured exception may be an exception caused and thrown by its own statement, or it may be an exception thrown by a called method or the Java runtime system. In other words, the exception that a method can catch must be an exception thrown by Java code somewhere. Simply put, exceptions are always thrown first and caught later.
Any Java code can throw exceptions, such as code written by yourself, code from the Java development environment package, or the Java runtime system. Anyone can throw an exception through Java's throw statement.
Any exception thrown from a method must use the throws clause.
Catching exceptions is achieved through try-catch statements or try-catch-finally statements.
Generally speaking, Java stipulates that checkable exceptions must be caught or declared to be thrown. Allows ignoring uncheckable RuntimeException and Error.
3.1 捕获异常:try、catch 和 finally
1.try-catch语句
在Java中,异常通过try-catch语句捕获。其一般语法形式为:
try { // 可能会发生异常的程序代码 } catch (Type1 id1){ // 捕获并处置try抛出的异常类型Type1 } catch (Type2 id2){ //捕获并处置try抛出的异常类型Type2 }
关键词try后的一对大括号将一块可能发生异常的代码包起来,称为监控区域。Java方法在运行过程中出现异常,则创建异常对象。将异常抛出监控区域之 外,由Java运行时系统试图寻找匹配的catch子句以捕获异常。若有匹配的catch子句,则运行其异常处理代码,try-catch语句结束。
匹配的原则是:如果抛出的异常对象属于catch子句的异常类,或者属于该异常类的子类,则认为生成的异常对象与catch块捕获的异常类型相匹配。
例1 捕捉throw语句抛出的“除数为0”异常。
public class TestException { public static void main(String[] args) { int a = 6; int b = 0; try { // try监控区域 if (b == 0) throw new ArithmeticException(); // 通过throw语句抛出异常 System.out.println("a/b的值是:" + a / b); } catch (ArithmeticException e) { // catch捕捉异常 System.out.println("程序出现异常,变量b不能为0。"); } System.out.println("程序正常结束。"); } }
运行结果:
程序出现异常,变量b不能为0。
程序正常结束。
例1 在try监控区域通过if语句进行判断,当“除数为0”的错误条件成立时引发ArithmeticException异常,创建 ArithmeticException异常对象,并由throw语句将异常抛给Java运行时系统,由系统寻找匹配的异常处理器catch并运行相应异 常处理代码,打印输出“程序出现异常,变量b不能为0。”try-catch语句结束,继续程序流程。
事实上,“除数为0”等ArithmeticException,是RuntimException的子类。而运行时异常将由运行时系统自动抛出,不需要使用throw语句。
例2 捕捉运行时系统自动抛出“除数为0”引发的ArithmeticException异常。
public static void main(String[] args) { int a = 6; int b = 0; try { System.out.println("a/b的值是:" + a / b); } catch (ArithmeticException e) { System.out.println("程序出现异常,变量b不能为0。"); } System.out.println("程序正常结束。"); } }
运行结果:
程序出现异常,变量b不能为0。
程序正常结束。
例2 中的语句:
System.out.println(“a/b的值是:” + a/b);
在运行中出现“除数为0”错误,引发ArithmeticException异常。运行时系统创建异常对象并抛出监控区域,转而匹配合适的异常处理器catch,并执行相应的异常处理代码。
由于检查运行时异常的代价远大于捕捉异常所带来的益处,运行时异常不可查。Java编译器允许忽略运行时异常,一个方法可以既不捕捉,也不声明抛出运行时异常。
例3 不捕捉、也不声明抛出运行时异常。
public class TestException { public static void main(String[] args) { int a, b; a = 6; b = 0; // 除数b 的值为0 System.out.println(a / b); } }
运行结果:
Exception in thread “main” java.lang.ArithmeticException: / by zero
at Test.TestException.main(TestException.java:8)
例4 程序可能存在除数为0异常和数组下标越界异常。
public class TestException { public static void main(String[] args) { int[] intArray = new int[3]; try { for (int i = 0; i <= intArray.length; i++) { intArray[i] = i; System.out.println("intArray[" + i + "] = " + intArray[i]); System.out.println("intArray[" + i + "]模 " + (i - 2) + "的值: " + intArray[i] % (i - 2)); } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("intArray数组下标越界异常。"); } catch (ArithmeticException e) { System.out.println("除数为0异常。"); } System.out.println("程序正常结束。"); } }
运行结果:
intArray[0] = 0
intArray[0]模 -2的值: 0
intArray[1] = 1
intArray[1]模 -1的值: 0
intArray[2] = 2
除数为0异常。
程序正常结束。
例4 程序可能会出现除数为0异常,还可能会出现数组下标越界异常。程序运行过程中ArithmeticException异常类型是先行匹配的,因此执行相匹配的catch语句:
catch (ArithmeticException e){ System.out.println("除数为0异常。"); }
需要注意的是,一旦某个catch捕获到匹配的异常类型,将进入异常处理代码。一经处理结束,就意味着整个try-catch语句结束。其他的catch子句不再有匹配和捕获异常类型的机会。
Java通过异常类描述异常类型,异常类的层次结构如图1所示。对于有多个catch子句的异常程序而言,应该尽量将捕获底层异常类的catch子 句放在前面,同时尽量将捕获相对高层的异常类的catch子句放在后面。否则,捕获底层异常类的catch子句将可能会被屏蔽。
RuntimeException异常类包括运行时各种常见的异常,ArithmeticException类和ArrayIndexOutOfBoundsException类都是它的子类。因此,RuntimeException异常类的catch子句应该放在 最后面,否则可能会屏蔽其后的特定异常处理或引起编译错误。
2. try-catch-finally语句
try-catch语句还可以包括第三部分,就是finally子句。它表示无论是否出现异常,都应当执行的内容。try-catch-finally语句的一般语法形式为:
try { // 可能会发生异常的程序代码 } catch (Type1 id1) { // 捕获并处理try抛出的异常类型Type1 } catch (Type2 id2) { // 捕获并处理try抛出的异常类型Type2 } finally { // 无论是否发生异常,都将执行的语句块 }
例5 带finally子句的异常处理程序。
public class TestException { public static void main(String args[]) { int i = 0; String greetings[] = { " Hello world !", " Hello World !! ", " HELLO WORLD !!!" }; while (i < 4) { try { // 特别注意循环控制变量i的设计,避免造成无限循环 System.out.println(greetings[i++]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("数组下标越界异常"); } finally { System.out.println("--------------------------"); } } } }
运行结果:
Hello world !
————————–
Hello World !!
————————–
HELLO WORLD !!!
————————–
数组下标越界异常
————————–
在例5中,请特别注意try子句中语句块的设计,如果设计为如下,将会出现死循环。如果设计为:
try { System.out.println (greetings[i]); i++; }
小结:
try 块:用于捕获异常。其后可接零个或多个catch块,如果没有catch块,则必须跟一个finally块。
catch 块:用于处理try捕获到的异常。
finally 块:无论是否捕获或处理异常,finally块里的语句都会被执行。当在try块或catch块中遇到return语句时,finally语句块将在方法返回之前被执行。在以下4种特殊情况下,finally块不会被执行:
1)在finally语句块中发生了异常。
2)在前面的代码中用了System.exit()退出程序。
3)程序所在的线程死亡。
4)关闭CPU。
3. try-catch-finally 规则(异常处理语句的语法规则):
1) 必须在 try 之后添加 catch 或 finally 块。try 块后可同时接 catch 和 finally 块,但至少有一个块。
2) 必须遵循块顺序:若代码同时使用 catch 和 finally 块,则必须将 catch 块放在 try 块之后。
3) catch 块与相应的异常类的类型相关。
4) 一个 try 块可能有多个 catch 块。若如此,则执行第一个匹配块。即Java虚拟机会把实际抛出的异常对象依次和各个catch代码块声明的异常类型匹配,如果异常对象为某个异常类型或其子类的实例,就执行这个catch代码块,不会再执行其他的 catch代码块
5) 可嵌套 try-catch-finally 结构。
6) 在 try-catch-finally 结构中,可重新抛出异常。
7) 除了下列情况,总将执行 finally 做为结束:JVM 过早终止(调用 System.exit(int));在 finally 块中抛出一个未处理的异常;计算机断电、失火、或遭遇病毒攻击。
4. try、catch、finally语句块的执行顺序:
1)当try没有捕获到异常时:try语句块中的语句逐一被执行,程序将跳过catch语句块,执行finally语句块和其后的语句;
2)当try捕获到异常,catch语句块里没有处理此异常的情况:当try语句块里的某条语句出现异常时,而没有处理此异常的catch语句块时,此异常将会抛给JVM处理,finally语句块里的语句还是会被执行,但finally语句块后的语句不会被执行;
3)当try捕获到异常,catch语句块里有处理此异常的情况:在try语句块中是按照顺序来执行的,当执行到某一条语句出现异常时,程序将跳到catch语句块,并与catch语句块逐一匹配,找到与之对应的处理程序,其他的catch语句块将不会被执行,而try语句块中,出现异常之后的语句也不会被执行,catch语句块执行完后,执行finally语句块里的语句,最后执行finally语句块后的语句;
图示try、catch、finally语句块的执行:
3.2 抛出异常
任何Java代码都可以抛出异常,如:自己编写的代码、来自Java开发环境包中代码,或者Java运行时系统。无论是谁,都可以通过Java的throw语句抛出异常。从方法中抛出的任何异常都必须使用throws子句。
1. throws抛出异常
如果一个方法可能会出现异常,但没有能力处理这种异常,可以在方法声明处用throws子句来声明抛出异常。例如汽车在运行时可能会出现故障,汽车本身没办法处理这个故障,那就让开车的人来处理。
throws语句用在方法定义时声明该方法要抛出的异常类型,如果抛出的是Exception异常类型,则该方法被声明为抛出所有的异常。多个异常可使用逗号分割。throws语句的语法格式为:
methodname throws Exception1,Exception2,..,ExceptionN { }
方法名后的throws Exception1,Exception2,…,ExceptionN 为声明要抛出的异常列表。当方法抛出异常列表的异常时,方法将不对这些类型及其子类类型的异常作处理,而抛向调用该方法的方法,由他去处理。例如:
import java.lang.Exception; public class TestException { static void pop() throws NegativeArraySizeException { // 定义方法并抛出NegativeArraySizeException异常 int[] arr = new int[-3]; // 创建数组 } public static void main(String[] args) { // 主方法 try { // try语句处理异常信息 pop(); // 调用pop()方法 } catch (NegativeArraySizeException e) { System.out.println("pop()方法抛出的异常");// 输出异常信息 } } }
使用throws关键字将异常抛给调用者后,如果调用者不想处理该异常,可以继续向上抛出,但最终要有能够处理该异常的调用者。
pop方法没有处理异常NegativeArraySizeException,而是由main函数来处理。
Throws抛出异常的规则:
1) 如果是不可查异常(unchecked exception),即Error、RuntimeException或它们的子类,那么可以不使用throws关键字来声明要抛出的异常,编译仍能顺利通过,但在运行时会被系统抛出。
2)必须声明方法可抛出的任何可查异常(checked exception)。即如果一个方法可能出现受可查异常,要么用try-catch语句捕获,要么用throws子句声明将它抛出,否则会导致编译错误
3)仅当抛出了异常,该方法的调用者才必须处理或者重新抛出该异常。当方法的调用者无力处理该异常的时候,应该继续抛出,而不是囫囵吞枣。
4)调用方法必须遵循任何可查异常的处理和声明规则。若覆盖一个方法,则不能声明与覆盖方法不同的异常。声明的任何异常必须是被覆盖方法所声明异常的同类或子类。
例如:
void method1() throws IOException{} //合法 //编译错误,必须捕获或声明抛出IOException void method2(){ method1(); } //合法,声明抛出IOException void method3()throws IOException { method1(); } //合法,声明抛出Exception,IOException是Exception的子类 void method4()throws Exception { method1(); } //合法,捕获IOException void method5(){ try{ method1(); }catch(IOException e){…} } //编译错误,必须捕获或声明抛出Exception void method6(){ try{ method1(); }catch(IOException e){throw new Exception();} } //合法,声明抛出Exception void method7()throws Exception{ try{ method1(); }catch(IOException e){throw new Exception();} }
判断一个方法可能会出现异常的依据如下:
1)方法中有throw语句。例如,以上method7()方法的catch代码块有throw语句。
2)调用了其他方法,其他方法用throws子句声明抛出某种异常。例如,method3()方法调用了method1()方法,method1()方法声明抛出IOException,因此,在method3()方法中可能会出现IOException。
2. 使用throw抛出异常
throw总是出现在函数体中,用来抛出一个Throwable类型的异常。程序会在throw语句后立即终止,它后面的语句执行不到,然后在包含它的所有try块中(可能在上层调用函数中)从里向外寻找含有与其匹配的catch子句的try块。
我们知道,异常是异常类的实例对象,我们可以创建异常类的实例对象通过throw语句抛出。该语句的语法格式为:
throw new exceptionname;
例如抛出一个IOException类的异常对象:
throw new IOException;
要注意的是,throw 抛出的只能够是可抛出类Throwable 或者其子类的实例对象。下面的操作是错误的:
throw new String(“exception”);
这是因为String 不是Throwable 类的子类。
如果抛出了检查异常,则还应该在方法头部声明方法可能抛出的异常类型。该方法的调用者也必须检查处理抛出的异常。
如果所有方法都层层上抛获取的异常,最终JVM会进行处理,处理也很简单,就是打印异常消息和堆栈信息。如果抛出的是Error或RuntimeException,则该方法的调用者可选择处理该异常。
package Test; import java.lang.Exception; public class TestException { static int quotient(int x, int y) throws MyException { // 定义方法抛出异常 if (y < 0) { // 判断参数是否小于0 throw new MyException("除数不能是负数"); // 异常信息 } return x/y; // 返回值 } public static void main(String args[]) { // 主方法 int a =3; int b =0; try { // try语句包含可能发生异常的语句 int result = quotient(a, b); // 调用方法quotient() } catch (MyException e) { // 处理自定义异常 System.out.println(e.getMessage()); // 输出异常信息 } catch (ArithmeticException e) { // 处理ArithmeticException异常 System.out.println("除数不能为0"); // 输出提示信息 } catch (Exception e) { // 处理其他异常 System.out.println("程序发生了其他的异常"); // 输出提示信息 } } } class MyException extends Exception { // 创建自定义异常类 String message; // 定义String类型变量 public MyException(String ErrorMessagr) { // 父类方法 message = ErrorMessagr; } public String getMessage() { // 覆盖getMessage()方法 return message; } }
3.3 异常链
1) 如果调用quotient(3,-1),将发生MyException异常,程序调转到catch (MyException e)代码块中执行;
2) 如果调用quotient(5,0),将会因“除数为0”错误引发ArithmeticException异常,属于运行时异常类,由Java运行时系统自动抛出。quotient()方法没有捕捉ArithmeticException异常,Java运行时系统将沿方法调用栈查到main方法,将抛出的异常上传至quotient()方法的调用者:
int result = quotient(a, b); // 调用方法quotient()
由于该语句在try监控区域内,因此传回的“除数为0”的ArithmeticException异常由Java运行时系统抛出,并匹配catch子句:
catch (ArithmeticException e) { // 处理ArithmeticException异常 System.out.println(“除数不能为0″); // 输出提示信息 }
处理结果是输出“除数不能为0”。Java这种向上传递异常信息的处理机制,形成异常链。
Java方法抛出的可查异常将依据调用栈、沿着方法调用的层次结构一直传递到具备处理能力的调用方法,最高层次到main方法为止。如果异常传递到main方法,而main不具备处理能力,也没有通过throws声明抛出该异常,将可能出现编译错误。
3)如还有其他异常发生,将使用catch (Exception e)捕捉异常。由于Exception是所有异常类的父类,如果将catch (Exception e)代码块放在其他两个代码块的前面,后面的代码块将永远得不到执行,就没有什么意义了,所以catch语句的顺序不可掉换。
3.4 Throwable类中的常用方法
注意:catch关键字后面括号中的Exception类型的参数e。Exception就是try代码块传递给catch代码块的变量类型,e就是变量名。catch代码块中语句”e.getMessage();”用于输出错误性质。通常异常处理常用3个函数来获取异常的有关信息:
getCause():返回抛出异常的原因。如果 cause 不存在或未知,则返回 null。
getMeage():返回异常的消息信息。
printStackTrace(): The object’s stack trace is output to the error output stream as the value of the field System.err.
Sometimes the code after the catch statement is ignored for the sake of simplicity, so that the try-catch statement becomes a decoration. Once an exception occurs during the running of the program, the exception handling will be ignored, and the cause of the error is difficult to find. .
4. Java common exceptions
Java provides some exceptions to describe frequently occurring errors. For these exceptions, some require programmers to catch or declare them to be thrown, and some are automatically caught and handled by the Java virtual machine. . Common exception classes in Java:
1. runtimeException subclass:
1. java.lang.ArrayIndexOutOfBoundsException
Array index out-of-bounds exception. Thrown when the index into the array is negative or greater than or equal to the array size.
2. java.lang.ArithmeticException
Arithmetic condition exception. For example: integer division by zero, etc.
3. java.lang.NullPointerException
Null pointer exception. This exception is thrown when the application attempts to use null where an object is required. For example: calling the instance method of the null object, accessing the properties of the null object, calculating the length of the null object, using the throw statement to throw null, etc. 4. java.lang.ClassNotFoundException
Class exception not found. This exception is thrown when the application attempts to construct a class based on a class name in string form, but cannot find the class file with the corresponding name after traversing the CLASSPAH.
5. java.lang.NegativeArraySizeException The array length is negative
6. java.lang.ArrayStoreException The array contains an incompatible value
7. java.lang.SecurityException Security exception
8. java.lang.IllegalArgumentException Illegal parameter exception
2.IOException
IOException: Exceptions that may occur when operating input streams and output streams.
EOFException File ended exception
FileNotFoundException File not found exception
3. Others
ClassCastException Type conversion exception class
ArrayStoreException Exception thrown when the array contains incompatible values
SQLException Operation database exception class
NoSuchFieldException Field not found exception
NoSuchMethodException Method not found exception thrown
NumberFormatException Exception thrown by converting string to number
StringIndexOutOfBoundsException String index out of range exception thrown
IllegalAccessException Access to a certain type of exception is not allowed
InstantiationException When the application attempts to create an instance of a class using the newInstance() method in the Class class, and the specified class object cannot be instantiated, this exception is thrown
5. Custom exception
Using Java's built-in exception class can Describes most exceptions that occur while programming. In addition, users can also customize exceptions. User-defined exception classes only need to inherit the Exception class.
Using custom exception classes in a program can be roughly divided into the following steps.
(1) Create a custom exception class.
(2) Throw an exception object through the throw keyword in the method. (3) If the exception is handled in the method that currently throws the exception, you can use the try-catch statement to capture and handle it; otherwise, use the throws keyword at the declaration of the method to indicate the exception to be thrown to the method caller, and continue with the next step. One step operation.
(4) Catch and handle exceptions in the caller of the exception method.
It has been mentioned in the above example of "using throw to throw an exception".