Java exception handling (the most detailed in the whole network)

Java exception handling

  Exceptions are some bugs in a program, but not all bugs are exceptions, and bugs are sometimes avoidable. For example, if your code is missing a semicolon, the result of running it will be an error java.lang.Error; if you use System.out.println(11/0), then you are dividing by 0. , which will throw a java.lang.ArithmeticException exception.

There are many reasons for exceptions, usually including the following categories:

  • The user has entered illegal data.
  • The file to open does not exist.
  • The connection is interrupted during network communication, or the JVM memory overflows

Some of these exceptions are caused by user errors, some by program errors, and others by physical errors. -

 

To understand how Java exception handling works, you need to master the following three types of exceptions:

  • Checked Exceptions : The most representative checked exceptions are those caused by user errors or problems, which the programmer cannot foresee. For example, when trying to open a file that does not exist, an exception occurs, and these exceptions cannot simply be ignored at compile time.
  • Runtime Exceptions :  Runtime exceptions are exceptions that may be avoided by the programmer. In contrast to checked exceptions, runtime exceptions can be ignored at compile time.
  • Errors :  Errors are not exceptions, but problems outside the programmer's control. Errors are usually ignored in code. For example, when the stack overflows, an error occurs, and they cannot be checked at compile time.

 

Java built-in exception class

The Java language defines some exception classes in the java.lang standard package.

Subclasses of the standard runtime exception classes are the most common exception classes. Since the java.lang package is loaded into all Java programs by default, most exceptions inherited from runtime exception classes can be used directly.

Java also defines some other exceptions according to each class library, the following table lists Java's unchecked exceptions.

abnormal Depiction
ArithmeticException This exception is thrown when an abnormal operation condition occurs. For example, an instance of this class is thrown when an integer is "divided by zero".
ArrayIndexOutOfBoundsException Exception thrown when accessing an array with an illegal index. If the index is negative or greater than or equal to the size of the array, the index is illegal.
ArrayStoreException Exception thrown when attempting to store an object of the wrong type into an array of objects.
ClassCastException Thrown when attempting to cast an object to a subclass that is not an instance.
IllegalArgumentException The exception thrown indicates that an invalid or incorrect parameter was passed to the method.
IllegalMonitorStateException The exception thrown indicates that a thread has attempted to wait on an object's monitor, or attempted to notify other threads that are waiting on an object's monitor without specifying a monitor themselves.
IllegalStateException Signal generated when a method is called at an illegal or inappropriate time. In other words, the Java environment or Java application is not in the proper state required by the requested operation.
IllegalThreadStateException Exception thrown when the thread is not in the proper state required by the requested operation.
IndexOutOfBoundsException Thrown when a sorting index (such as sorting an array, string, or vector) is out of range.
NegativeArraySizeException Thrown if the application attempts to create an array of negative size.
NullPointerException null This exception is thrown when the application attempts to use the object where it is required 
NumberFormatException Thrown when an application attempts to convert a string to a numeric type, but the string cannot be converted to the proper format.
SecurityException Exception thrown by the security manager to indicate a security violation.
StringIndexOutOfBoundsException This exception is  String thrown by the method to indicate that the index is either negative or exceeds the size of the string.
UnsupportedOperationException Thrown when the requested operation is not supported.

The following table lists the checked exception classes that Java defines in the java.lang package.

abnormal Depiction
ClassNotFoundException This exception is thrown when the application attempts to load a class and cannot find the corresponding class.
CloneNotSupportedException  Thrown when Object a method in a class is  called  to clone clone an object, but the object's class cannot implement the  interface.Cloneable
IllegalAccessException This exception is thrown when access to a class is denied.
InstantiationException Thrown when an attempt is made to create an instance of a class using  Class a  newInstance method in the class and the specified class object cannot be instantiated because it is an interface or an abstract class.
InterruptedException A thread is interrupted by another thread, throwing this exception.
NoSuchFieldException The requested variable does not exist
NoSuchMethodException The requested method does not exist

 

catch exception

Exceptions can be caught using the try and catch keywords. Try/catch blocks are placed where exceptions can occur.

The code in the try/catch block is called guard code, and the syntax for using try/catch is as follows:

try
{
   // Program code 
} catch (ExceptionName e1)
{
   // Catch block 
}

 

The Catch statement contains a declaration of the type of exception to be caught. When an exception occurs in the guarded code block, the catch block after the try is checked.

 

如果发生的异常包含在 catch 块中,异常会被传递到该 catch 块,这和传递一个参数到方法是一样。

多重捕获块

一个 try 代码块后面跟随多个 catch 代码块的情况就叫多重捕获。

多重捕获块的语法如下所示:

try{
   // 程序代码
}catch(异常类型1 异常的变量名1){
  // 程序代码
}catch(异常类型2 异常的变量名2){
  // 程序代码
}catch(异常类型2 异常的变量名2){
  // 程序代码
}

上面的代码段包含了 3 个 catch块。

可以在 try 语句后面添加任意数量的 catch 块。

如果保护代码中发生异常,异常被抛给第一个 catch 块。

如果抛出异常的数据类型与 ExceptionType1 匹配,它在这里就会被捕获。

如果不匹配,它会被传递给第二个 catch 块。

如此,直到异常被捕获或者通过所有的 catch 块。

 

throws/throw 关键字:

如果一个方法没有捕获一个检查性异常,那么该方法必须使用 throws 关键字来声明。throws 关键字放在方法签名的尾部。

也可以使用 throw 关键字抛出一个异常,无论它是新实例化的还是刚捕获到的。

下面方法的声明抛出一个 RemoteException 异常:

import java.io.*;
public class className
{
  public void deposit(double amount) throws RemoteException
  {
    // Method implementation
    throw new RemoteException();
  }
  //Remainder of class definition
}

finally关键字

finally 关键字用来创建在 try 代码块后面执行的代码块。

无论是否发生异常,finally 代码块中的代码总会被执行。

在 finally 代码块中,可以运行清理类型等收尾善后性质的语句。

finally 代码块出现在 catch 代码块最后,语法如下:

try{
  // 程序代码
}catch(异常类型1 异常的变量名1){
  // 程序代码
}catch(异常类型2 异常的变量名2){
  // 程序代码
}finally{
  // 程序代码
}

最后总结特别需要注意的地方:

  • catch 不能独立于 try 存在。
  • 在 try/catch 后面添加 finally 块并非强制性要求的。
  • try 代码后不能既没 catch 块也没 finally 块。
  • try, catch, finally 块之间不能添加任何代码。

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326645685&siteId=291194637