Java exception handling two


The content of the article is selected from Shang Silicon Valley, jdk8, eclipse environment

throws throws an exception

Exception handling in java . As mentioned above, there are two ways to handle exceptions in java. One is to use try-catch-finally block to handle the exception, and the other is to throw an exception and hand it over to the method that calls the method. deal with.

The manifestation of throwing an exception is the throws exception type

The code following the exception code is still no longer executed

The sample code is as follows

package com.atguigu.java;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ExceptionTest2 {
    
    
	
	public static void main(String[] args) {
    
    
		try {
    
    
			method2();
		} catch (FileNotFoundException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e){
    
    
			e.printStackTrace();
		}
	}
	
	public static void method2() throws FileNotFoundException,IOException{
    
    
		method1();
	}
	
	public static void method1() throws FileNotFoundException,IOException{
    
    
		File file = new File("hello1.txt");
		FileInputStream fis = new FileInputStream(file);
		
		int data = fis.read();
		while(data != -1){
    
    
			System.out.print((char)data);
			data = fis.read();
		}
		
		fis.close();
	}
}

Analyzing the code, in the original method1 method, there are two types of possible problems: FileNotFoundException and IOException, so the processing method here is to throw the two exceptions generated by the system upwards and throw them into the method2 method. If the method2 method is not used The try-catch method handles exceptions, then the exceptions must be reported to the main method. In fact, the main method can also be thrown up and thrown to the JVM. However, in general, the main method must use try-catch to handle exceptions to prevent JVM It can't handle the exception and hangs up.

All in all, the calling method must resolve the exception of the called method. Throws exceptions (throwing exceptions) can also be regarded as one of the methods to handle exceptions.

The above code can also be written as

package com.atguigu.java;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ExceptionTest2 {
    
    
	
	public static void main(String[] args) {
    
    
		try {
    
    
			method2();
		}  catch (IOException e){
    
    
			e.printStackTrace();
		}
	}
	
	public static void method2() throws IOException{
    
    
		method1();
	}
	
	public static void method1() throws FileNotFoundException,IOException{
    
    
		File file = new File("hello1.txt");
		FileInputStream fis = new FileInputStream(file);
		
		int data = fis.read();
		while(data != -1){
    
    
			System.out.print((char)data);
			data = fis.read();
		}
		
		fis.close();
	}
}

Because IOException is the parent class of FileNotFoundException, it can also be understood as IOException covers FileNotFoundException. Therefore, when method2 throws an exception, you can only write IOException. In the main method, only IOException is handled. Then the difference between this method and the previous method is that if the two exception handling methods are the same, then there is no need to throwFileNotFoundException exception, just throw an IOException exception, if the two exception handling methods are different , Just follow the previous writing method to handle two different exceptions separately.

The try-catch method really handles the exception, while the throws method just throws the exception to the caller of the method, and does not really handle the exception.

The exception thrown by the overriding method of the subclass must not be greater than the exception thrown by the overriding method of the parent class

The sample code is as follows

import java.io.FileNotFoundException;
import java.io.IOException;

public class OverrideTest {
    
    

}

class SuperClass{
    
    
	public void method() throws IOException{
    
    
		
	}
}

class SubClass extends SuperClass{
    
    
	public void method() throws FileNotFoundException{
    
    
		
	}
}

The exception thrown by the subclass override method must be no greater than the exception thrown by the parent class by the override method. Of course, the subclass may not throw exceptions.

class SubClass extends SuperClass{
    
    
	public void method() {
    
    
		
	}
}

This writing is also legal, simply understood as the anomaly is infinitely small, so small that there is no anomaly.

The reason why the exception thrown by the subclass override method must not be greater than the exception thrown by the superclass by the override method is because when polymorphism is used, it is necessary to ensure that the exception of the parent class can cover the exception of the subclass. Demo code as follows

package com.atguigu.java;

import java.io.FileNotFoundException;
import java.io.IOException;

public class OverrideTest {
    
    
	
	public static void main(String[] args) {
    
    
		OverrideTest test = new OverrideTest();
		test.display(new SubClass());
	}
	
	public void display(SuperClass s){
    
    
		try {
    
    
			s.method();
		} catch (IOException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class SuperClass{
    
    
	public void method() throws IOException{
    
    
		
	}
}

class SubClass extends SuperClass{
    
    
	public void method() {
    
    
		
	}
}

When using polymorphism, if the subclass throws an exception, the exception type must be no greater than the exception type of the parent class.

How to choose which way to handle exceptions in development

  • I just said that the exception thrown by the subclass override method must not be greater than the exception thrown by the override method of the parent class, and the non-throwing exception is understood as the smallest exception, then if the overridden method in the parent class does not throw If an exception occurs, then it is not allowed to throw an exception in the subclass, and the exception can only be handled by try-catch.
  • If the three methods a, b, and c are in a progressive relationship, that is, the result of method a is called by method b, and the result of method b is called by method c, then these three methods are best used when declaring throws throws an exception. If the d method calls the three methods a, b, and c, put the three methods a, b, and c into the try structure to solve the problem. Because if try-catch is used when the three methods of a, b, and c are declared, although the compiler can definitely pass, but logically there may be a problem (because the three methods of a, b, and c are Progressive relationship), then the result of the operation is definitely wrong. It is better to use the try-catch structure in the d method to solve the exception in a unified way to avoid logical confusion.
  • Try-catch and throws are two ways to handle exceptions, it is best not to use them together, because try-catch has solved the problem, and then throws out, then the method of calling this method has to write a try-catch structure to handle the exception .
  • Again, to resolve runtime exceptions, try-catch is generally not used to handle exceptions, but to modify the code to handle exceptions. Try-catch at best serves as an error message to remind the user where the problem is, but it cannot really handle the exception.

Handling exceptions manually

There are two ways to generate an exception object, one is the system automatically generates (throws), the other is to manually generate an exception object by yourself, and throw (throw)

There are specific application scenarios for manually throwing exception objects. The demo code is as follows

package com.atguigu.java2;

public class StudentTest {
    
    
	public static void main(String[] args) {
    
    
		Student s = new Student();
		s.regist(-1001);
		System.out.println(s);
	}
}

class Student{
    
    
	private int num ;
	 
	public void regist(int num){
    
    
		if(num > 0)
			this.num = num;
		else
			System.out.println("输入格式非法");
	}

	@Override
	public String toString() {
    
    
		return "Student [num=" + num + "]";
	}
	
}

The result of the operation is

Illegal input format
Student [num=0]

If we normally input a positive number, then Student [num=value of positive number] will be output directly , which is the rewritten content of toString.

But here we have entered a negative number, the input format is illegal, and we don't want to call the toString method to output the value anymore, so we need to manually throw an exception.

Type of object that manually throws an exception

There are two types of manually thrown exception objects, one is RuntimeException and the other is Exception.

RuntimeException

The compiler will not report an error when it detects RuntimeException, because this is a runtime exception. If Exception is checked, an error will be reported.

class Student{
    
    
	private int num ;
	 
	public void regist(int num){
    
    
		if(num > 0)
			this.num = num;
		else
//			System.out.println("输入格式非法");
			throw new RuntimeException("输入格式非法");
	}

The result of the operation is
Insert picture description here
that the compiler will not report an error when compiling, because the compiler detects that the runtime exception will not be processed. Runtime exceptions will only be reported at runtime.
Press Alt+/ to view the constructor of the exception type. The RuntimeException class has a constructor called RuntimeException(String arg0), so you can put a string in it, and the string will be printed out on the console. Here you can think of the previous text Talk about the e.getMessage() method.

Exception

You can also throw an Exception object manually. Because Exception is not a runtime exception, it is the parent class of runtime exceptions and compile-time exceptions. If the exception is not handled at compile time, the compiler will report an error.

package com.atguigu.java2;

import javax.management.RuntimeErrorException;

public class StudentTest {
    
    
	public static void main(String[] args) {
    
    
		Student s = new Student();
		try {
    
    
			s.regist(-1001);
		} catch (Exception e) {
    
    
			
//			e.printStackTrace();
			System.out.println(e.getMessage());
		}
		System.out.println(s);
	}
}

class Student{
    
    
	private int num ;
	 
	public void regist(int num) throws Exception{
    
    
		if(num > 0)
			this.num = num;
		else
//			System.out.println("输入格式非法");
//			throw new RuntimeException("输入格式非法");
			throw new Exception("输入格式非法");
	}

	@Override
	public String toString() {
    
    
		return "Student [num=" + num + "]";
	}
	
}

The result of the operation is

Illegal input format

The throw in the regist method is to manually throw the exception object, and the throws in the method declaration is one of the ways we handle exceptions, and the try-catch structure is used to handle the exception in the main method.

Since Exception inherits the parent class throwable, e.getMessage() is the method that calls the parent class structure throwable

    public String getMessage() {
    
    
        return detailMessage;
    }

The constructor of Exception here is

    public Exception(String message) {
    
    
        super(message);
    }

Inherited from the parent throwable

    public Throwable(String message) {
    
    
        fillInStackTrace();
        detailMessage = message;
    }

Therefore, the value assigned by the constructor can be output by the e.getMessage() method.

User-defined exception

User-defined exceptions can be written by referring to the writing method of the exception object in the java library

  • User-defined exceptions can be inherited from RuntimeException and Exception
  • User-defined exceptions must have a global constant serialVersionUID (serial number), which is understood as the identifier of the class.
  • Provide overloaded constructor
package com.atguigu.java2;

public class MyException extends RuntimeException{
    
    
    static final long serialVersionUID = -70348971907766939L;
    
    public MyException(){
    
    
    	
    }
    
    public MyException(String msg){
    
    
    	super(msg);
    }
}

Modify it in the previous code

	public void regist(int num) throws Exception{
    
    
		if(num > 0)
			this.num = num;
		else
//			System.out.println("输入格式非法");
//			throw new RuntimeException("输入格式非法");
//			throw new Exception("输入格式非法");
			throw new MyException("不能输入负数");
	}

The result of the operation is

Cannot enter negative numbers

Note that MyException is a runtime exception, and the runtime exception may not be handled, and the compiler will not report an error. Because MyException inherits RuntimeException, it can run without throwing Exception. (The thrown Exception is the parent class of MyException, legal) (throws is also one of the methods to handle exceptions)

	public void regist(int num) {
    
    
		if(num > 0)
			this.num = num;
		else
//			System.out.println("输入格式非法");
//			throw new RuntimeException("输入格式非法");
//			throw new Exception("输入格式非法");
			throw new MyException("不能输入负数");
	}

This is legal, and the result of the operation is

Cannot enter negative numbers

If MyException is inherited from Exception, then the exception manually thrown in the regist method must be processed immediately , otherwise the compiler will report an error

public class MyException extends Exception{
    
    

Either throw or try-catch processing in the regist method.

	public void regist(int num) throws MyException {
    
    
		if(num > 0)
			this.num = num;
		else
//			System.out.println("输入格式非法");
//			throw new RuntimeException("输入格式非法");
//			throw new Exception("输入格式非法");
			throw new MyException("不能输入负数");
	}

It is also legal to throw Exception, which is the parent class of MyException.

Guess you like

Origin blog.csdn.net/Meloneating/article/details/115027620