Location>code7788 >text

Java Exceptions White Label Edition

Popularity:897 ℃/2024-08-15 23:48:17

What's an anomaly?

Any irregularity that interrupts the normal program flow while the program is running is called an error or exception. Exceptions include user-caused exceptions and

Anomalies caused by the system.

Examples include: broken network connection, operator out of bounds, loaded class not found

Causes and classification of anomalies

1. Causes of anomalies

Exceptions are generated in Java for three main reasons:

  • Exceptions generated by errors in writing program code, such as array out-of-bounds, null pointer exceptions, etc., are called unchecked exceptions and generally need to be handled in the class

  • Java Internal Error Occurrence Exception, Java Virtual Machine Generated Exception

  • Exceptions generated manually by the throw statement are called checked exceptions and are generally used to give the method caller some necessary information.

2. Abnormal classification

Throwable: is the root exception class, which derives from two important subclasses, Error and Exception.

  • Exception class Indicates a predictable exception that can be handled or recovered;
  • Error Class Indicates an unanticipated exception that cannot be handled or recovered.

Exception Handling Methods

1. Catch and handle exceptions

try-catch-finally statement

The try-catch-finally statement catches exceptions generated in the program and then handles them with different handlers for different situations.

The Basic Format of a try-catch-finally Statement
try{
    Java statements // One or more Java statements that may throw an exception.
}catch(Exception e){
    Java statements //Exception type exceptions (all handled exceptions) executed code
}finally{
    // Code that is always executed regardless of the presence or absence of an exception
}
Implementation:
  • Case 1: The code in the try block has no exceptions, the code in the catch block is not executed, and the code after the catch block is executed;
  • Case 2: code in the try block has an exception, the exception type in the catch matches (same or parent class), Java generates the corresponding exception object, and the Java system looks for a matching catch block. Execute the code after the catch block, the code in the try block will not be executed;
  • Case 3: code in try block has exception, exception type in catch does not match, do not execute the code in catch block, only execute the code in finally{}, do not execute the rest of the code after the catch block.
  • Scenario 4: A piece of code may raise multiple types of exceptions. When an exception is raised, the exception types of each catch are viewed sequentially, and only the exception code in the first catch that matches the type of the exception is executed, while the exception code in the other catches will not be executed.

Note: How exceptions are handled in a catch block: one way - custom content output

Example 1: Case 1

public class ExceptionDemo01 {
    public static void main(String[] args) {
        
        int b = 2; int b = 1
        try {
            
            (c);
        } catch (ArithmeticException e) { // catch ArithmeticException exception, for beginners, it is recommended to just write Exception as it catches all exceptions
            ("The divisor cannot be zero"); }
        }finally {
            ("End of program"); }
        }
    }
}
//Run the results:
5
End of program

Example 2: Case 2

public class ExceptionDemo01 {
    public static void main(String[] args) {
        
        
        try {
            int c = a / b; // division is 0, an exception occurs
            (c); } catch (ArithmeticException)
        } catch (ArithmeticException e) { //Exception type match in catch, execute code after catch block
            ("Divisor can't be 0"); }finally {
        }finally {
            ("End of program"); }
       }
    }
}
//Running results
The divisor cannot be 0
End of program

Example 3: Situation 3

import ;

public class ExceptionDemo01 {
    public static void main(String[] args) {
        
        
        try {
            int c = a / b; // division is 0, an exception occurs
            (c); } catch (InputMismatch)
        } catch (InputMismatchException e) { //Exception type mismatch in catch, do not execute catch block code
            ("Divisor can't be 0"); }finally { //Execute catch block code
        }finally { //Execute
            ("End of program"); }
        }

        ("End of program 0000"); //not executed
    }
}
//Running results
End of program

2. Throw exceptions in methods

Two ways to throw exceptions: throw and throws

throw is used to throw exceptions in code.

The format is as follows:

throw new Exception type.

throws is used to throw an exception in a method.

The format is as follows:

method name() throws exception type {
  // method body
}

Example:

// Extracting a method: dividing two numbers
public static void devide() throws Exception { //throws
        int a = 10; int b = 0; //throws
        int b = 0; // if(b == 0) { // if b equals 0, throw an exception.
        if(b == 0) { //throw an exception if b equals 0
            //Artificially create an exception object
            throw new Exception("Divisor cannot be 0"); //throw
        }else {
            ("Dividing two numbers: "+a/b);

        }
    }
Difference between throw and throws:
  • The location is different: throw is inside the method; throws is at the method's declaration.
  • Different content: throw + exception object; throws + exception type
  • The role is different: throw: the source of exceptions, create exceptions; throws at the method declaration, tell the method caller, this method may appear I declare these exceptions. The caller then handles the exception: either by itself or by continuing to throw the exception.

Propagation of anomalies

When a method throws an exception, if the current method doesn't catch the exception, the exception is thrown to the higher level calling method until it encounters some try.... .catch is caught.

public class Main{
    try{
        process1();
    }catch(Exception e){
        ();
    }
}

static void process1(){
    process2();
}

static void process2(){
    ("abc"); //throw an exception
}
printStackTrace() method

can print out the method call stack, which is very useful for debugging errors (each level of the method call gives the line number of the source code, so you can directly locate the code that generated the exception).

Java Exception Structure Diagram

Classification of Exception

RuntimeException Runtime exception (non-checked exception)

The compiler is not forced to handle exceptions. Common runtime exceptions (non-checked exceptions)

NullpointerException:Null Pointer Exception
ClassCastException:Type forced conversion exception.
IllegalArgumentException:Passing Illegal Argument Exception
IndexOutOfBoundsException:SubscriptOutOfBoundsException
NumberFormatException:Number Format Exception.
ArrayIndexOutOfBoundsException: Array out of bounds exception.
ArrayStoreException: Array type inconsistency exception.
ArithmeticException: Arithmetic exceptions (except 0 exceptions).
BufferOverflowException: Buffer overflow exception.

CheckedException Non-runtime exception (checked exception)

The compiler forces the exception to be handled, otherwise a compilation error is displayed. Common non-runtime exceptions (checked exceptions):

ClassNotFoundException:Cannot find the specified class exception.
IOException:IO operation exception
FileNotFoundException:File not found exception
SQLException:SQL Statement Exception
InterruptedException:InterruptedException


Characteristics of the exception handling mechanism

  1. Exception propagation allows exceptions to be passed to the appropriate location and then handled, making exception handling in the Java language more flexible;
  2. It is possible to separate the logic code being executed from the exception handling code at the source code level, making it easier to read and maintain the code;
  3. Excessive use of exception handling will reduce the efficiency of program execution and increase the complexity of the syntax.