Exceptions in Java

Posted by mrMarcus on Wed, 27 Oct 2021 18:56:27 +0200

Abnormal System:

Error: Serious problem, no need to handle
Exception: An exception class that represents a problem that the program itself can handle

  • RuntimeException: Not checked at compile time, after problems, we need to come back and modify the code
  • Non-RuntimeException: must be handled at compile time or the program cannot be compiled.

Default Processing Scheme for JVM

If something goes wrong with the program and we don't do anything about it, eventually the JVM will do it by default

exception handling

If there are exceptions to the program, we need to handle them by ourselves. There are two options:

1. try...catch in exception handling

  • Format:
	try {
            Code with possible exceptions;
        } catch(Exception class variable name) {
            Handling code for exceptions;
        }

Execution process:
The program starts from the code inside the try.
When an exception occurs, an exception class object is automatically generated and submitted to the java runtime system.
When the java runtime system receives an exception object, it will go to the catch to find a matching exception class and handle the exception after finding it.
After execution is complete, the program can continue executing.

Example: int array out of bounds

		System.out.println("start");
        try{
            int[] arr = {1, 2, 3};
            System.out.println(arr[3]);//Beyond bounds
        }catch(ArrayIndexOutOfBoundsException e){//Exception type
            e.printStackTrace();//Print Exception Reason
        }
        //Continue with follow-up
        System.out.println("End");

Output:

start
 End
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
	at com.test1.Demo.main(Demo.java:10)

Membership methods for Throwable

Method NameExplain
public String getMessage()Returns the throwable's detailed message string
public String toString()Return this throwable short description
public void printStackTrace()Output exception error information to console
  1. public String getMessage():
		System.out.println("start")
		try{
            int[] arr = {1, 2, 3};
            System.out.println(arr[3]);//Beyond bounds
        }catch(ArrayIndexOutOfBoundsException e){//Exception type
            System.out.println(e.getMessage());
        }
        System.out.println("End");

Output:

start
Index 3 out of bounds for length 3
 End
  1. Replace getMessage() with toString():
System.out.println(e.toString());

Output:

start
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
 End
  1. public void printStackTrace() is used above. This method has the most complete information and is generally used.

Differences between compile-time and run-time exceptions

All RuntimeException classes and their subclasses are called runtime exceptions, and the other exceptions are compile-time exceptions.

  • Compile-time exception: Processing must be displayed or the program will fail to compile
  • Runtime exceptions: no display handling is required or can be handled as compiled exceptions

throws for exception handling

Format: throws exception class name;
Note: This formatting method follows the parentheses of the method

  • Compile-time exceptions must be handled by two methods: try...catch...or throws. If throws is used, who calls whom to handle them in the future
  • Runtime exceptions can be left untreated and we need to come back to modify the code after a problem occurs

throws simply throw exceptions, do not handle exceptions, exception handling or try...catch...

public class Demo {
    public static void main(String[] args) {

        System.out.println("start");
        try {//Receive thrown exceptions
            method();
        } catch (ParseException e) {
            e.printStackTrace();//Handle Exceptions
        }

        System.out.println("End");
    }

    //Throw exception
    public static void method() throws ParseException {//Throw the corresponding exception type
        String s = "2001-03-14";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = new Date();
        d = sdf.parse(s);
        System.out.println(d);//Continue execution
    }
}

Custom Exception

Format:

public class Exception Class Name extends Exception {
    Parametric construction;
    Parametric construction;
}

Example:

public class ScoreException extends Exception {

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

The difference between throw and throws

throwsthrow
Used after method declarations, followed by exception class namesUsed within a method body, followed by an exception object name
Indicates that an exception was thrown and handled by the caller of the methodIndicates that an exception was thrown and is handled by a statement within the method body
Indicates a possibility of an exception that may not necessarily occurExecuting throw must throw an exception

Example: Teacher gives students a score, the normal score is between 0 and 100. Write a program to check if the score is normal.

/inherit Exception,Override construction method
public class ScoreException extends Exception {
    public ScoreException() {}
    public ScoreException(String message){
        super(message);
    }
}
public class teacher {
    
    public void checkScore(int score) throws ScoreException {//throw
        //Determine if the score is between 0 and 100
        if(score < 0 || score > 100){
            throw new ScoreException("You gave the wrong score");//An exception occurred
        }else{
            System.out.println("Normal score");
        }
    }
}
import java.util.Scanner;

public class Demo {
    public static void main(String[] args) {
        //Get points
        Scanner s = new Scanner(System.in);
        System.out.print("Please enter a score:");
        int score = s.nextInt();

        //Detect if score is normal
        teacher t = new teacher();
        try {
            t.checkScore(score);
        } catch (ScoreException e) {//Custom exception types
            e.printStackTrace();//Handle Exceptions
        }
    }
}

Output:

Please enter a score: 60
 Normal score
Please enter a score: 111
com.test2.ScoreException: You gave the wrong score
	at com.test2.teacher.checkScore(teacher.java:8)
	at com.test2.Demo.main(Demo.java:15)

Topics: Java