Java: Exceptions in brief

Needless to say, the concept of exceptions, we all know what it means. When the program is running, many situations will lead to abnormal events, such as:
(1) The file you want to open does not exist
(2) The network connection is interrupted
(3) Operands Exceeding the predetermined range
(4) The accessed data cannot be opened
(5) The class file being loaded is missing, etc.
Simply put, the problem that occurs during the runtime of the Java code is an exception. In Java, there is a very complete mechanism to handle exceptions. It encapsulates the exception information into a class. When a problem occurs, an exception class object is created and the related information about the exception is output on the console.
For example:
when the subscript of the program crosses the boundary, the related exception information will be output.

package demo1;

public class demo {
    
    
	public static void main(String[] args) {
    
    
		int[] arr = {
    
    1,2,3};
		System.out.println(arr[4]);
	}
}

Insert picture description here

1. Throw exceptions (throw) and method declaration exceptions (throws)

In java, a throw keyword is provided to throw a specified exception object.
Steps:
(1). Create an exception object. (Encapsulate some prompt information. Note: The prompt information can be written
by yourself) (2). Inform the user of the abnormal object through the throw keyword.
Use format:

//throw用在方法内,抛出一个异常对象,将这个异常对象传递到调用者处,并结束当前方法的执行。
//格式:throw new 异常类名(参数);
例如:throw new NullPointerExction("要访问的arr数组不存在!");

For example, in the following code, if no processing is done, a null pointer exception will occur.

package demo1;

public class demo {
    
    
	public static void main(String[] args) {
    
    
		int[] arr = null;
		int i = getarray(arr);
		System.out.println(i);
	}
	public static int getarray(int[] arr) {
    
    
		int i = arr[arr.length-1];
		return i*2;
	}
}

```![在这里插入图片描述](https://img-blog.csdnimg.cn/20200924215541648.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzODI1Mzc3,size_16,color_FFFFFF,t_70#pic_center)

此时如果我们给程序加上throw语句,程序便会报错,不能运行
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200924221528423.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzODI1Mzc3,size_16,color_FFFFFF,t_70#pic_center)
这是因为没有在方法中声明异常,就相当于一个人生病了,但是他没有表现出来,也告诉别人,所以没人知道他生病了一样。此时我们就需要用到另一个关键字throws,它的作用是用在方法声明上,标明此方法可能出现异常,请调用者处理。声明异常后,程序便可以正常运行了,需要注意的是,当在方法后使用throws关键字后,在main函数后面也要使用throws关键字进行异常声明,不然程序会报错。

```java
package demo1;

public class demo {
    
    
	public static void main(String[] args) throws Exception{
    
    
		
		int[] arr = null;
		int i = getarray(arr);
		System.out.println(i);
	}
	public static int getarray(int[] arr) throws Exception{
    
    
		if(arr == null) {
    
    
			throw new Exception("传递的数组不存在!");
		}
		if(arr.length == 0){
    
    
			throw new Exception("数组中没有任何元素!!");
			
		}
		int i = arr[arr.length-1];
		return i*2;
	}
}

Insert picture description here
Now the exception information printed by the program is the exception information we wrote in throw new Exeption();.

2.try…cath…finally

The above is just a method of exception handling. In Java, try...cath...finally can also be used for exception handling.
format:

try{
    
    
	被检测的代码
	可能出现异常的代码
}catch(异常类的名称 变量){
    
    
	异常处理方式
	循环,判断,调用方法,变量
}finally{
    
    
	必须要执行的代码
}

example:

package demo1;

public class demo {
    
    
	public static void main(String[] args){
    
    
		
		int[] arr = null;
		try {
    
    
			int i = getarray(arr);
			System.out.println(i);
		}catch(NullPointerException ex) {
    
    
			System.out.println(ex);
		}
		
	}
	public static int getarray(int[] arr) throws NullPointerException{
    
    
		if(arr == null) {
    
    
			throw new NullPointerException("传递的数组不存在!");
		}
		if(arr.length == 0){
    
    
			throw new NullPointerException("数组中没有任何元素!!");
			
		}
		int i = arr[arr.length-1];
		return i*2;
	}
}

Insert picture description here
As you can see, using this method we don't need to use the throws keyword after the method. In the above example, we did not use the content of the finally code block. Finally is optional in the try...cath...finally structure. Regardless of whether there is an exception in the try statement block, the block in the finally statement will be executed. Therefore, the biggest function of the finally statement block is for the release of resources. Prevent the leakage of resources.
Note: The statement in the finally statement block will not be executed in only one case (after the exception is caught, the virtual machine will be terminated with the Sytem.exit(0) statement in the catch statement block)

Guess you like

Origin blog.csdn.net/qq_43825377/article/details/108654995