java exception handling

Posted by PW on Thu, 13 Jan 2022 16:43:42 +0100

Chapter VI: exception handling one

1. Overview of anomalies one

1.1 introduction of abnormality one

1.2 concept of abnormality two

2. Anomaly classification three

2.1 abnormal system three

2.2 Throwable......................................................................................................................... 3

2.3 error four

2.4 exception five

2.4.1 abnormality during operation five

2.4.2 compile time exception seven

3. Exception handling seven

3.1 analysis of abnormal generation process seven

3.2 throw eight

3.3 declared exceptions nine

3.4 try catch finally eleven

3.4.1 try catch combination eleven

3.4.2 try catch finally combination mode thirteen

3.4.3 try finally combination fifteen

4. Custom exception sixteen

4.1 custom exception format sixteen

4.2 custom exception usage sixteen

5. Supplement of abnormal skills seventeen

5.1 exceptions in method rewriting seventeen

5.2 abnormal chain eighteen

Exception overview

Introduction of exceptions

In real life, all things are developing and changing, and there will be all kinds of abnormal phenomena.

For example, people get sick when they grow up.

In actual work, the situation encountered can not be very perfect. For example, for a module you write, the user input does not necessarily meet your requirements, your program wants to open a file, the file may not exist or the file format is wrong, you want to read the data in the database, the data may be empty, etc. Our program runs again, the memory or hard disk may be full, and so on.

During the operation of the software program, it is very likely to encounter these abnormal problems just mentioned. We call them exceptions, which means exceptions. These, exceptions, or exceptions, how to make the program we write handle reasonably and exit safely without crashing.

Requirement: to obtain the element value in the array according to the index, we need to consider various exceptions. The pseudo code is as follows:

[example] get the element value in the array according to the index (for illustration only, can't run)

public static int getValue(int[] arr, int index) {

    // When the index is negative

    if(index < 0) {

       System.out.println("Index cannot be negative!!");

       return ???; // What should I return here?

    }  

    // When the index is greater than or equal to the length of the array

    if(index >= arr.length) {

       System.out.println("Index cannot be greater than or equal to array length!!");

       return ???; // What should I return here?

    }

    // Normal return element value

    return arr[index];

}

This approach has several disadvantages:

  1. Logic code and error handling code together!
  2. The exceptions that programmers themselves need to consider are more complex and have higher requirements for programmers themselves!
  3. No matter how it is handled, it may not meet the development needs!!!

So how do we deal with the above exceptions? In fact, JAVA provides us with a mechanism for handling exceptions, that is, when the program makes an error, the program exits safely.

Concept of exception

In actual development, exceptions are also a kind of things from the perspective of object-oriented. We can extract them upward as exception classes. This exception class can describe some abnormal phenomena and encapsulate them as objects.

Let's start with our first exception object and analyze how the exception mechanism works.

[example] abnormal analysis cases

public class ExceptionTest {

    public static void main(String[] args) {

       test();

    }

    public static void test() {

       int x = 3 / 0;

       System.out.println("x:" + x);

    }

}

 

Operation effect diagram

java handles exceptions in an object-oriented way. When the program has a problem, it will create an exception class object and throw information related to the exception (such as the location and reason of the exception).

Anomaly classification

Abnormal system

JDK # defines many exception classes, which correspond to various possible exception events. All exception objects are derived from an instance of Throwable class. If the built-in exception class cannot meet the needs, you can also create your own exception class.

Thorwable class (indicating that it can be thrown) is the superclass of all exceptions and errors. The two direct subclasses are Error and Exception, which represent errors and exceptions respectively.

Let's take a look at the architecture diagram of exceptions in java:

 

Anomaly system classification

Throwable class is a superclass of all exceptions or errors. It has two subclasses: Error and Exception, which represent errors and exceptions respectively. Exceptions are divided into runtime exceptions and compile time exceptions.

Error and runtime exception. Because the program does not check for exceptions at compile time, it is also called unchecked exception.

Compile time exception. It is also called checked exception because the program can be checked out at compile time

Introduction to common methods of Throwable:

Method name

describe

public String getMessage()

Returns the detailed message string for this throwable.

public String toString()

Returns a short description of this throwable

public void printStackTrace()

Prints trace information for the stack of exceptions

3 error

Error class is the parent class of all error classes in java. It describes the internal errors and resource exhaustion errors of the java runtime system. This kind of error is beyond our control. It is also a very rare error, indicating that the system JVM is in an unrecoverable crash state. It is generated and thrown by the JVM, such as OutOfMemoryError, ThreadDeath, etc.

Therefore, errors are difficult to deal with. Ordinary developers (of course not you) can't deal with these errors. We can't deal with such errors in programming.

 

java. Error class in Lang package

Here are some common Error cases:

[example] memory overflow case

public class ExceptionDemo {

    public static void main(String[] args) {

       // The array needs 1G of memory, which will cause memory overflow

       int[] but = new int[1024*1024*1024]; // 1K-->1M-->1G

       System.out.println(but);

    }

}

 

Memory overflow. The required memory is beyond the memory range managed by the java virtual machine

[example] stack overflow case

public class ExceptionDemo {

    public static void main(String[] args) {

       test();

    }

    public static void test() {

       test(); // Keep calling recursively, which will cause stack overflow

    }

}

 

Stack overflow: this error is thrown when the level of recursive call is too deep to cause stack overflow

(abnormal)

Exception class is the parent class of all exception classes, and its subclasses correspond to various possible exception events. Error is an error that cannot be handled by the program, but exception is an exception that can be handled by the program itself. These exceptions should be handled as much as possible in the program.

Difference between Error and Exception:

  1. When I was driving on the road, a pig rushed in the middle of the road. I braked. This is called an anomaly.
  2. I was driving on the road and the engine broke down. I stopped. It's called a mistake.

When did the engine break down? Can we ordinary drivers take care of it? No. When the engine breaks down is a matter for the engine manufacturer of the automobile factory.

Exception s fall into two categories:

1. RuntimeException runtime exception

2. CheckedException compile time exception

Runtime exception

All subtype exceptions of RuntimeException and others belong to run time exceptions. For example: NullPointerException, ClassCastException, IndexOutOfBoundsException, ArithmeticException, etc. It is also called UnCheckedException because the exception cannot be checked out when the program is compiled.

Runtime exceptions are generally caused by program logic errors, so when writing programs, we should try our best to avoid such exceptions from a logical point of view.

When runtimeexceptions occur, the system will automatically detect them and hand them over to the default exception handler (the virtual machine takes over and handles them). Users do not have to deal with them. For example, no one has ever handled the NullPointerException exception, which is a runtime exception, and this exception is one of the most common exceptions.  

ArithmeticException exception, which is thrown when an arithmetic condition is abnormal. For example, an integer of "divide by zero" will throw an instance of this class.

[example] ArithmeticException exception case

public static void main(String[] args) {

    int x = 0;

    // Judge the x variable here to avoid the ArithmeticException exception

    int y = 3 / x;

    System.out.println("y:" + y);

}

 

ArithmeticException exception

NullPointerException (null pointer exception) occurs when the program accesses the member variable or method of an empty object and the member of an empty array.

[example] NullPointerException exception case

public static void main(String[] args) {

    int[] arr = null;

    // Judge whether arr is null here to avoid NullPointerException exception

    System.out.println(arr.length);

}

 

NullPointerException exception

ClassCastException exception occurs when an object is converted to a subclass that does not belong to an instance.

[example] ClassCastException exception case

// Parent class

class Animal {}

// Subclass

class Dog extends Animal {}

class Cat extends Animal {}

// Test class

public class RuntimeDemo {

    public static void main(String[] args) {

       Animal animal = new Dog();

       // Use instanceof to judge the type before transformation, so as to avoid ClassCastException exceptions

       Cat cat = (Cat)animal;

    }

}

 

ClassCastException exception

ArrayIndexOutOfBoundsException exception occurs when an illegal index is used to access an array. The index is negative or greater than or equal to the size of the array.

[example] ArrayIndexOutOfBoundsException exception exception case

public static void main(String[] args) {

    int[] arr = new int[3];

    // Before obtaining array elements, first judge the array index

    System.out.println(arr[-1]);

}

 

ArrayIndexOutOfBoundsException exception exception

Compile time exception

Exception and its subclasses (excluding run exceptions) are collectively referred to as compile time exceptions. It is also called CheckedException because an exception can be detected during compilation.

Common compile time exceptions, such as IOException, SQLException, and user-defined exceptions inherited from Exception.

For compile time exceptions, we are forced to handle these exceptions at compile time, otherwise the program cannot be compiled. Therefore, in the face of such exceptions, whether we like it or not, we can only deal with possible exceptions by ourselves.

[example] compile time exception cases

 

CheckedException must be processed, otherwise it cannot be compiled

exception handling

Analysis of exception generation process

When running the following program, the program will generate an array index out of bounds exception: ArrayIndexOfBoundsException. We use diagrams to analyze the process of exception generation.

[example] abnormal generation process case

// Tool class

class ArraysTool {

    // Gets the value of the corresponding element in the array according to the index

    public static int getValue(int[] arr, int index) {

       int value = arr[index];

       return value;

    }

}

// Test class

public class ExceptionDemo {

    public static void main(String[] args) {

       int[] arr = {1, 2, 3};

       int value = ArraysTool.getValue(arr, 3);

       System.out.println(value);

       }

}

Diagram of the execution process of the above procedures:

 

Throw exception

When writing a program, we must consider the problem of the program. For example, when defining a method, the method needs to accept parameters. Then, when calling the method to use the received parameters, you first need to judge the validity of the parameter data. If the data is illegal, you should tell the caller to pass in the legal data. In this case, you need to tell the caller by throwing an exception.

In java, a throw keyword is provided, which is used to throw a specified exception object. Then, throw an exception

How to operate?

1. Create an exception object and encapsulate some prompt information (the information can be written by yourself).

2. You need to inform the caller of this exception object, which can be completed by using the keyword throw #.

Throw is used in a method to throw an exception object, pass the exception object to the caller, and end the execution of the current method.

Throw exception format: throw new exception class name (parameter list);

[example] throw exception cases

// Tool class

class ArraysTool {

    // Gets the value of the corresponding element in the array according to the index

    public static int getValue(int[] arr, int index) {

       // Judge whether the index is legal

       if(index < 0 || index >= arr.length) {

           // Throw an illegal index exception when the index is illegal.

           // This will end the execution of the current method and notify the caller of the exception

           throw new ArrayIndexOutOfBoundsException("Illegal index");

       }

       int value = arr[index];

       return value;

    }

}

// Test class

public class ExceptionDemo {

    public static void main(String[] args) {

       int[] arr = {1, 2, 3};

       // Call the method to get the element at the specified index in the array

       int value = ArraysTool.getValue(arr, 3);

       System.out.println(value);

    }

}

If the index of the above code is illegal, the following exception will be thrown!

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: illegal index

    at com.bjsxt.exceprion.ArraysTool.getValue(ExceptionDemo.java:10)

    at com.bjsxt.exceprion.ExceptionDemo.main(ExceptionDemo.java:20)

Declare exceptions (throws)

Statement: identify the problem and report it to the caller. If a compile time exception is thrown in the method through throw , without capturing and processing (this method will be explained later), it must be declared through the throw keyword for the caller to handle.

Declaration exception format: modifier} return value type} method name (parameter list) throws} exception class name 1, exception class name 2... {}

[example] throws declaration exception case

//Tool class

class ArraysTool {

    // Use the throws keyword to declare exceptions and report possible exceptions to the caller.

    public static int getValue(int[] arr, int index) throws ArrayIndexOutOfBoundsException {

       // Judge whether the index is legal

       if(index < 0 || index >= arr.length)

           throw new ArrayIndexOutOfBoundsException("Illegal index");

// Return element value

       return arr[index];

    }

}

Throws is used to declare exception classes. If multiple exceptions may occur in this method, multiple exception classes can be written after throws, separated by commas.

[example] throws , declare multiple exception cases

//Tool class

class ArraysTool {

    // Use the throws keyword to declare exceptions and report possible exceptions to the caller.

    public static int getValue(int[] arr, int index) throws NullPointerException, ArrayIndexOutOfBoundsException {

       // Determine whether arr is null

       if(null == arr)

           throw new NullPointerException("object arr by null");

       // Judge whether the index is legal

       if(index < 0 || index >= arr.length)

           throw new ArrayIndexOutOfBoundsException("Illegal index");

// Return element value

       return arr[index];

    }

}

When a runtime exception occurs in the program, the method definition does not need to throw to declare the exception, and the caller does not need to capture and handle the exception (i.e. there is no try catch). The system will throw the exception to the top layer by default.

When a non runtime exception occurs in the program, either catch it with a try catch statement or throw it with a throw statement declaration, otherwise the compilation will not pass.

[example] throws , declare non runtime exception cases

// Demo class

class Demo {

    /*

     * Because NullPointerException is a runtime exception, you do not need to use the throws Declaration on the method

     * FileNotFoundException is a non runtime exception. Here, you should use the throws Declaration on the method, otherwise the compilation will not pass

     */

    public void test(Object obj, String path) throws FileNotFoundException {

       // Judge whether obj is null

       if(null == obj)

           throw new NullPointerException("obj Cannot be null");

       // Create a file byte read stream object. If the file address does not exist, a FileNotFoundException exception will be thrown

       FileInputStream is = new FileInputStream(path);

    }

}

// Test class

public class ThrowsExceptionDemo {

    /*

     * main()If the FileNotFoundException exception exception is not captured in the method, it should continue to be thrown on the main() method and finally handed over to the JVM for processing

     */

    public static void main(String[] args) throws FileNotFoundException {

       // Call the test() method in the Demo class

       new Demo().test(new Object(), "D://abc.txt");

    }

}

Try catch finally

If an exception occurs in the program and you can't solve it yourself, you can declare the exceptions and report them to the caller for handling.

If the exception can be solved by yourself, you don't need to declare the exception, but catch the exception (try catch finally) and handle the exception in the catch block.

A try statement must have at least one catch statement block or one finally statement block.  

Combination mode

Try catch , combination: detect exceptions in the code and pass the detected exceptions to , catch , for processing.

Capture exception format:

try {

    // Statements that need to be detected.

} catch(Exception class variable) { // parameter

    // Exception handling statement.

}

try: write the code that may generate exceptions in this code block. This code is the scope of one-time capture and processing. During execution, when any statement generates an exception, the code behind the paragraph will be skipped. One or more types of exception objects may be generated and thrown in the code, and the catch statements behind them should deal with these exceptions respectively.

Catch: it is used to catch certain exceptions and handle the caught exceptions. The parameter in catch is the exception object caught (that is, the exception object thrown). We can get the specific information of the exception according to the exception object.

[example] try catch exception cases

// Tool class

class ArraysTool {

    // ArrayIndexOutOfBoundsException is a runtime exception, so you don't need to force throws declaration

    public static int getValue(int[] arr, int index) {

       // Judge whether the index is legal

       if(index < 0 || index >= arr.length) {

           throw new ArrayIndexOutOfBoundsException("Illegal index");

       }

       // Return element value

       return arr[index];

    }

}

// Test class

public class TryCatchDemo {

    public static void main(String[] args) {

       int[] arr = {1, 2, 3, 4};

       try {

           // Getting the value of an element may throw an exception object

           // If an exception occurs, the execution of the current code block is ended

           int value = ArraysTool.getValue(arr, 5);

           System.out.println("value:" + value); // Do not execute

       } catch(ArrayIndexOutOfBoundsException e) { // The exception object whose parameter is thrown

           // Get exception information

           System.out.println("msg:" + e.getMessage());

           // Print an exception object that overrides the toString() method

           System.out.println("exception:" + e);

           // Output stack exception

           e.printStackTrace();

       }

       // The code executes regardless of whether an exception occurs

       System.out.println("over"); // implement

    }

}

One {try} multiple} catch} combination: detect exceptions in the code and pass the detected exceptions to {catch} for processing. Each exception information is captured and processed differently.

// Tool class

class ArraysTool {

    public static int getValue(int[] arr, int index) throws Exception {

       // Determine whether arr is null

       if(null == arr)

           throw new NullPointerException("object arr Cannot be null");

       // Judge whether the index is greater than or equal to arr.length

       if(index >= arr.length)

           throw new ArrayIndexOutOfBoundsException("Index cannot be greater than or equal to array length");

       // Determine whether the index is less than 0

       if(index < 0)

           throw new Exception("Index cannot be less than 0");

       // Return element value

       return arr[index];

    }

}

// Test class

public class TryCatchDemo {

    public static void main(String[] args) {

       int[] arr = {1, 2, 3, 4};

       try {

           // Getting the value of an element may throw an exception object

           int value = ArraysTool.getValue(arr, -5);

           System.out.println("value:" + value); // Do not execute

       } catch (NullPointerException e) { // Null pointer exception

           // Get exception information

           System.out.println("msg:" + e.getMessage());

           // Output stack exception

           e.printStackTrace();

       } catch (ArrayIndexOutOfBoundsException e) {// Exception when index is greater than or equal to array length

           // Get exception information

           System.out.println("msg:" + e.getMessage());

           // Output stack exception

           e.printStackTrace();

       }

       // When there are multiple catches, the catch of the parent exception should be placed at the bottom!!!

       catch (Exception e) {  // Index less than 0 exception

           // Get exception information

           System.out.println("msg:" + e.getMessage());

           // Output stack exception

           e.printStackTrace();

       }

       // The code executes regardless of whether an exception occurs

       System.out.println("over"); // implement

    }

}

Note: this exception handling method requires that the exceptions in multiple {catch} cannot be the same, and if there is a relationship between child and parent exceptions in {catch}, the child exceptions shall be handled in the above} catch}, and the parent exceptions shall be handled in the following} catch}.

Combination mode

Try catch finally combination: detect exceptions, pass them to {catch} for processing, and release resources in {finally}.

Capture exception format:

try {

    // Statements that need to be detected.

} catch(Exception class variable) { // parameter

    // Exception handling statement.

} finally {

    // A statement that must be executed to release resources.

}

try: write the code that may generate exceptions in this code block. This code is the scope of one-time capture and processing.

Catch: it is used to catch certain exceptions and handle the caught exceptions. One key can correspond to multiple catches.

Finally: there are some specific codes that need to be executed whether an exception occurs or not. In addition, because the exception will cause program jump, some statements cannot be executed. Finally solves this problem. The code stored in the finally code block must be executed.

[example] try catch finally catch exception cases

// Tool class

class ArraysTool {

    public static int getValue(int[] arr, int index) {

       // Determine whether arr is null

       if(arr == null)

           throw new NullPointerException("object arr Cannot be null");

       // Judge whether the index is legal

       if(index < 0 || index >= arr.length)

           throw new ArrayIndexOutOfBoundsException("Illegal index");

       // Return element value

       return arr[index];

    }

}

// Test class

public class TryCatchDemo {

    public static void main(String[] args) {

       int[] arr = {1, 2, 3, 4};

       try {

           // Getting the value of an element may throw an exception object

           int value = ArraysTool.getValue(arr, -2);

           System.out.println("value:" + value); // Do not execute

       } catch (NullPointerException e) { // Null pointer exception

           // Get exception information

           System.out.println("msg:" + e.getMessage());

           // Output stack exception

           e.printStackTrace();

       } catch (ArrayIndexOutOfBoundsException e) { // Illegal index exception

           // Get exception information

           System.out.println("msg:" + e.getMessage());

           // Output stack exception

           e.printStackTrace();

       } finally {

           // Whether an exception occurs or not, you need to execute the code in finally.

           // The code in the finally block is generally used to release resources.

           System.out.println("implement finally");

       }

       // The code executes regardless of whether an exception occurs

       System.out.println("over"); // implement

    }

}

Note: even if you add return in try or catch, the code in finally will be executed unless you call system exit(0); Exit the virtual machine so that the code in finally will not be executed.

[example] add a return case in try or catch

public static void main(String[] args) {

    int[] arr = {1, 2, 3, 4};

    try {

       // Getting the value of an element may throw an exception object

       int value = arr[4];

       System.out.println("value:" + value);

       return; // Add return;

} catch (ArrayIndexOutOfBoundsException e) {

       return; // Add return;

    } finally {

       // Add a return operation to try or catch, and the code in the finally block will still be executed

       System.out.println("implement finally"); // implement

    }

}

[example] add system. In try or catch exit(0); case

public static void main(String[] args) {

    int[] arr = {1, 2, 3, 4};

    try {

       // Getting the value of an element may throw an exception object

       int value = arr[3];

       System.out.println("value:" + value);

       System.exit(0); // Exit virtual machine operation

    } catch (ArrayIndexOutOfBoundsException e) {

       System.exit(0); // Exit virtual machine operation

    } finally {

       // Add system. In try or catch exit(0); Operation, the code in the finally block will not be executed

       System.out.println("Do not execute finally"); // Do not execute

    }

}

Combination mode

Try finally} combination: exception detection is performed on the code. After an exception is detected, because there is no catch, it will also be thrown by the default} jvm. Exceptions are not captured and handled. However, the resources enabled by the function need to be closed, and all finally only close the resources.

Capture exception format:

try {

    // Statements that need to be detected.

} finally {

    // A statement that must be executed to release resources.

}

[example] try finally combination case

// Throw Exception

public static void main(String[] args) throws Exception {

    try {

       // Non runtime exceptions, if not caught with catch, should be declared on the method

       throw new Exception("Custom exception");

    } finally {

       // Close resource operation...

    }

}

Custom exception

Custom exception format

In the program, you may encounter the problem that any standard exception class is not fully described. In this case, you can create your own exception class.

All exception classes in java inherit Throwable or subclasses of Throwable. In this way, the exception can be thrown, because the exception system has a castability, that is, the throw keyword can be used.

A custom class should contain two constructors: one is the default constructor and the other is the constructor with details.

Custom exception format:

class Custom exception name extends Exception or RuntimeException {

    public Custom exception name() {

       // Call the parent class parameterless constructor by default

    }

    public Custom exception name(String msg) {

       // Call the constructor with exception information of the parent class

       super(msg);

    }

}

Custom exception usage

In the parameterized construction method of the {Person} class, judge the age range. If the age is negative or greater than 130 years old, throw

AgeOutOfBoundsException exception.

[example] user defined exception use cases

// Custom exception class

class AgeOutOfBoundsException extends Exception {

    // Nonparametric construction method

    public AgeOutOfBoundsException() {}

    // Parametric construction method

    public AgeOutOfBoundsException(String msg) {

       super(msg);

    }

}

// Person class

class Person {

    int age;

    public Person(int age) throws AgeOutOfBoundsException {

       // Judge whether the age is legal

       if(age < 0 || age >= 130) {

           throw new AgeOutOfBoundsException("Illegal anomaly of age value");

       }

       // Assign attributes

       this.age = age;

    }

}

// Test class

public class MyException {

    public static void main(String[] args) {

       try {

           // When initializing the object, AgeOutOfBoundsException may be thrown

           Person p = new Person(140);

           System.out.println("age:" + p.age);

       } catch (AgeOutOfBoundsException e) {

           // Get exception information

           System.out.println("msg:" + e.getMessage());

           // Output stack exception

           e.printStackTrace();

       }

    }

}

What is the difference between inheriting custom Exception from Exception or inheriting RuntimeException?  

  1. Inherited exceptions are non runtime exceptions. If their exceptions are not caught (try catch), you must declare throws on the method to tell the caller to catch them.
  2. Inheriting RuntimeException is a runtime exception. There is no need to declare throws on the method, and the caller can also not catch try catch. Once the code throws an exception, the program will hang up, and the JVM will display the exception information on the log window, so that the caller can see the exception and modify the code.

Abnormal skill supplement

Exceptions in method overrides

Principle: the exception scope of a subclass declaration cannot exceed the scope of a parent class declaration.

  1. If the parent class method does not declare an exception, the child class override method cannot declare an exception.
class Parent {

    public void show(){}

}

class Child extends Parent {

    public void show() throws Exception {} // Compilation error

}
  1. If the parent class throws an exception, the child class can only declare the exception of the parent class or the child class of the exception.
class AAException extends Exception {}

class BBException extends AAException {}

class Parent {

    public void show() throws AAException {}

}

class Child extends Parent {

    // public void show() {} / / no exceptions are declared. The compilation passes

    // Declaring the parent class of the parent class method exception, compilation error

    // public void show() throws Exception {}

    // Declare the same exception or subclass of the exception as the parent method, and compile it

    // public void show() throws AAException {} / / compilation passed

    public void show() throws BBException {}// Compile passed

    // There can be multiple exceptions declared by subclasses, but they must be exceptions with the same parent method or subclasses of the exception

    public void show() throws BBException, AAException {}// Compile passed

}

Explanation of abnormal chain

Exceptions need to be encapsulated, but encapsulation alone is not enough. Exceptions also need to be passed. The friendly identification and friendly interface function of a system is, on the one hand, the way to deal with unexpected situations in the system on the other hand.

Sometimes we catch an exception and throw another exception, which forms an exception chain.

[example] chain case

// Custom exception

class DenominatorZeroException extends Exception {

    public DenominatorZeroException() {}

    public DenominatorZeroException(String msg) {

       super(msg);

    }

}

// Calculator class

class Calculator {

    // Division operation

public static int division(int num, int den) throws DenominatorZeroException {

       int result = 0;

       try {

           result = num/den;

       }

       catch(ArithmeticException e) {

           // Throw a more detailed exception

           throw new DenominatorZeroException("Denominator cannot be 0");

       }

       return result;

    }

}

public class ExceptionTest07 {

    public static void main(String[] args) {

       try {

           // When two numbers are divided, arithmetic exceptions can occur

           Calculator.division(5, 0);

       } catch (DenominatorZeroException e) {

           e.printStackTrace();

       }

    }

}

5.3 try-with-resource

As we all know, all opened system resources, such as streams, files, Socket connections, etc., need to be manually closed by the developer. Otherwise, with the continuous operation of the program, resource leakage will accumulate into major production accidents.

At jdk1 Before 7, if we wanted to close resources, we had to do it in the finally code block.

[example] how to close resources before JDK7

/**

 * Test class

 */

public class Test {

    public static void main(String[] args) throws IOException {

        FileInputStream inputStream = null;

        try {

            // Create a byte input stream. Note: if the "file.txt" file does not exist in the project, an exception will be thrown

            inputStream = new FileInputStream("file.txt");

            // Perform the operation of storing data, and omit...

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } finally {

            if (inputStream != null) {

                // Close flow

                inputStream.close();

            }

        }

    }

}

The correct posture for closing resources in JDK7 and later: try with resource. The syntax format is:

try(/*Resources that need to be closed*/){

    // Exception prone code

}catch(Exception e) {

    // Handling exceptions

}

Definition of Resource: all implemented java.lang.AutoCloseable Interface (where it includes the implementation of java.io.Closeable Can be used as a resource.

[example] verify try with resource

/**

 * Resource class

 */

class Resource implements AutoCloseable {

    public void sayHello() {

        System.out.println("hello");

    }

    @Override

    public void close() throws Exception {

        System.out.println("Resource is closed");

    }

}

/**

 * Test class

 */

public class Test{

    public static void main(String[] args) {

       try(Resource resource = new Resource()) {

            resource.sayHello();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

The output result is:

 

[example] when there are multiple open resources

/**

 * Resource class

 */

class Resource1 implements AutoCloseable {

    public void sayHello() {

        System.out.println("Resource1 hello");

    }

    @Override

    public void close() throws Exception {

        System.out.println("Resource is closed");

    }

}

class Resource2 implements AutoCloseable {

    public void sayHello() {

        System.out.println("Resource2 hello");

    }

    @Override

    public void close() throws Exception {

        System.out.println("Resource is closed");

    }

}

/**

 * Test class

 */

public class Test{

    public static void main(String[] args) {

       try(Resource1 r1 = new Resource1(); Resource2 r2 = new Resource2()) {

            r1.sayHello();

            r2.sayHello();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

The output result is:

 

Release resources through try with resource. Even if there are many resources, the code can be written very succinctly. If you use jdk1 If you close resources in the way before 7, the more resources you have, the more nested you will be when you close resources with fianlly.

Topics: Java Back-end JavaSE