java tutorial: Java exception

A java exception is an event that occurs during the execution of a java program that disrupts the normal flow of instructions.

Exception class structure

All exception and error types are subclasses of the Throwable class, which is the base class of the hierarchy.

  • Error
           Used to indicate serious problems that a reasonable application should not try to catch.
    Java programs usually don’t catch errors. Errors usually occur when serious faults occur, and they are outside the scope of Java programs.
  • Exception : mainly divided into two categories
    • IOException, I/O input and output exceptions, IOException and its subclasses are also called “Checked Exceptions
    • RuntimeException, JVM runtime exception, RuntimeException is called “Unchecked Exceptions“.

Checked Exceptions

Except for RuntimeException, Error and their subclasses, they all belong to checkedException, and they are all defined inside the java.lang library. The Java compiler requires that the program must catch or declare to throw such an exception.

Exception handling

Default exception handling process:

  1. When an error occurs inside a method, the method will create an exception object and give it to the runtime system(JVM), that is, throw an exception. This object contains error information, error type and the state of the program when the error occurs.
  2. After the method throws an exception, the runtime system will try to search for code blocks that can handle the exception in the method call stack in the reverse order of calling the method.
  3. If the type of the thrown exception object matches the type that the handler can handle, it is considered that a suitable handler has been found, and the runtime system will pass the exception to the handler for processing.
  4. If the runtime system searches all the methods on the call stack and does not find a suitable exception handler, the runtime system will hand over the exception object to the default exception handler (it is a part of the runtime system). The program will print abnormal information and terminate the program abnormally.

Program exception handling method

try…catch keyword
  • Use the try and catch keywords to catch exceptions.
  • The try/catch code block is placed where the exception may occur.

Syntax of try/catch:

try {
   // Code block
} catch(ExceptionName e1) {
   //Catch block
}

# Multiple catch block
try{
   // Code block
}catch(ExceptionName1 e1){
   //Catch block1
}catch(ExceptionName2 e2){
   //Catch block2
}catch(ExceptionName3 e2){
   //Catch block2
}

Note: When there are multiple exception catch blocks, they can be parallel, or parent-child relationship from above to below, that is, the child class is at the top of the catch block and the parent class is at the bottom.

Example

package com.example.exception;

public class Demo {
    public static void main(String[] args) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

throws/throw keywords

Throws :
is a keyword in Java that is used in the signature of a method to indicate that the method may throw one of the listed types of exceptions. Callers of these methods must use try-catch blocks to handle exceptions.

Throw:
is a keyword in java, used to explicitly throw an exception in a method or any code block.

A method can declare to throw multiple exceptions, separated by commas.

Example

package com.example.exception;

import java.io.FileNotFoundException;

public class Demo {
    public static void main(String[] args) {
        Integer size = -1;
        String path = "/tmp/test.txt";

        try {
            testThrowException(path, size);
        }catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        System.out.println("Execute the main thread code");

    }

    public static void testThrowException(String path, Integer size) throws IllegalArgumentException, FileNotFoundException {
        if(size < 0) {
            throw new IllegalArgumentException("Illegal parameter");
        }

        if(!"/tmp/test.log".equals(path)) {
            throw new FileNotFoundException("File not found");
        }

        System.out.println("Execute the code");
    }
}

finally keyword

The finally keyword is used to create a code block to be executed after the try code block. Regardless of whether an exception occurs, the code in the finally code block will always be executed. Usually finally code block, used to run cleanup and other finishing work.

syntax


try{
   // Code block
}catch(ExceptionName1 e1){
   //Catch block1
}catch(ExceptionName2 e2){
   //Catch block2
}finally{
   //Catch block2
}

Example

package com.example.exception;

public class Demo1 {
    public static void main(String[] args) {
        int result = test();
        System.out.println(result);
    }

    public static int test() {
        int i = 1;
        try {
            i++;
            System.out.println("try block, i = " + i);
            return i;
        } catch (Exception e) {
            i--;
            System.out.println("catch block i = " + i);
        } finally {
            i = 10;
            System.out.println("finally block i = " + i);
        }
        return i;
    }
}

Add a Comment

Your email address will not be published. Required fields are marked *