Java Foundation (10) -- exception

abnormal

  • Overview of exceptions

    An exception is an abnormal condition in the program

Abnormal architecture

The JVM handles exceptions by default

  • If there is a problem with the program, we do not do any processing. Finally, the JVM will do the default processing. The processing method includes the following two steps:

  • The name of the exception, the cause of the error and the location of the exception are output to the console

  • Program stop

Try catch finally exception handling

  • Define format

    try {
    	Possible exception codes;
    } catch(Exception class name variable name) {
    	Exception handling code;
    }finally{
        //The finally statement block is bound to execute whether or not an exception occurs
    }
    
  • Execution process

    • The program starts from the code in try
    • If there is an exception in the try statement block, it will jump to the corresponding catch for execution. If there is no exception in the content of the try statement block, the program will not execute the content in the catch statement block and continue to execute downward. In any case, finally must be executed
    • After execution, the program can continue to execute
public class exceptionTest1 {
	public static void main(String[] args) {
		String[] arr = {"145","54","68"};
		try{
			System.out.println(arr[3]);
		}catch(Exception e){
			System.out.println("Array out of bounds exception");
		}finally{
			System.out.println("Code that must be executed");
		}
		System.out.println("Last code");
	}
}
/*
Array out of bounds exception
 Code that must be executed
 Last code
*/

Throwable member method

  • common method

    Method nameexplain
    public String getMessage()Returns the detailed message string for this throwable
    public String toString()Returns a short description of this throw
    public void printStackTrace()Output the abnormal error message to the console

    Sample code

public class exceptionTest1 {
	public static void main(String[] args) {
		String[] arr = {"145","54","68"};
		try{
			System.out.println(arr[3]);
		}catch(Exception e){
			System.out.println(e.getMessage());//3
			e.printStackTrace();
			/*
			 java.lang.ArrayIndexOutOfBoundsException: 3
	at Day0820am.exceptionTest1.main(exceptionTest1.java:18)
			 */
			System.out.println("Array out of bounds exception");
			System.out.println(e.toString());
			//java.lang.ArrayIndexOutOfBoundsException: 3
		}finally{
			System.out.println("Code that must be executed");
		}
		System.out.println("Last code");
	}
}
/*
3
java.lang.ArrayIndexOutOfBoundsException: 3
	at Day0820am.exceptionTest1.main(exceptionTest1.java:18)
Array out of bounds exception
java.lang.ArrayIndexOutOfBoundsException: 3
 Code that must be executed
 Last code

*/

The difference between compile time exceptions and runtime exceptions

  • Compile time exception

    • Are all Exception classes and their subclasses
    • The processing must be displayed, otherwise the program will have an error and cannot be compiled
  • Runtime exception

    • Are RuntimeException class and its subclasses
    • You do not need to display the handling, but you can also handle the exception as you do at compile time

Handling exceptions in throws mode

  • Define format

    public void method() throws Exception class name {
        
    }
    
  • Sample code

package Day0820am;

import java.text.SimpleDateFormat;
import java.util.Date;

public class exceptionTest3 {
	public static void main(String[] args) {
//		method();// If you do not try, an error will be reported
		try {
			method();
		} catch (Exception e1) {
			e1.printStackTrace();
			System.out.println("Array out of bounds exception");
		}
		try {
			method2();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void method2() throws Exception{
		String s = "2098-08-20";
		SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
		Date d = sdf.parse(s);//If there are no throws, an error will be reported
		System.out.println(d);
		
	}

	private static void method() throws Exception{
		int[] arr = {1,2,3,4};
		System.out.println(arr[4]);
	}

}
/*
java.lang.ArrayIndexOutOfBoundsException: 4
	at Day0820am.exceptionTest3.method(exceptionTest3.java:32)
	at Day0820am.exceptionTest3.main(exceptionTest3.java:10)
Array out of bounds exception
Wed Aug 20 00:00:00 CST 2098

*/

matters needing attention

  • The throws format follows the parentheses of the method
  • Exceptions must be handled during compilation. There are two processing schemes: try... catch... Or throws. If the throw scheme is adopted, who will call who to handle them in the future
  • Runtime exceptions can not be handled. After a problem occurs, we need to come back and modify the code

The difference between throws and throw

throwsthrow
Used after the method declaration, followed by the exception class nameUsed in the method body, followed by the exception object name
Indicates that an exception is thrown and handled by the caller of the methodIndicates that an exception is thrown and handled by the statement in the method body
Indicates a possibility of exceptions that do not necessarily occurExecuting throw must have thrown some kind of exception

Custom exception class

  • Custom exception class
package Day0820am;

public class ScoreException extends Exception{
	public ScoreException(){}
	public ScoreException(String message){
		super(message);
	}
}
  • Teacher class
package Day0820am;
public class Teacher {
	public void checkScore(double score) throws ScoreException{
		if(score<0.0 || score>100.0){
			throw new ScoreException("The score you entered is wrong. The score should be 0-100 between");
		}else{
			System.out.println("Normal performance");
		}
	}
}
  • Test class
package Day0820am;

import java.util.Scanner;

public class Test1 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter a score:");
		
		double score = sc.nextDouble();
		Teacher t = new Teacher();
		
		try {
			t.checkScore(score);
		} catch (ScoreException e) {
			e.printStackTrace();
		}
	}
	/*
	 Please enter a score:
200
Day0820am.ScoreException: The score you entered is wrong. The score should be between 0-100
	at Day0820am.Teacher.checkScore(Teacher.java:7)
	at Day0820am.Test1.main(Test1.java:15)
	
Please enter a score:
-7
Day0820am.ScoreException: The score you entered is wrong. The score should be between 0-100
	at Day0820am.Teacher.checkScore(Teacher.java:7)
	at Day0820am.Test1.main(Test1.java:15)

Please enter a score:
95
 Normal performance

	 */
}

Keywords: Java

Added by genistaff on Tue, 21 Dec 2021 20:34:31 +0200