Introduction to methods of handling exceptions in Java

Various errors may occur in the program, such as user input errors, device errors, storage space is full, or code errors. We collectively call them "program exceptions". In Java, you can use "exception handlers" to handle these exceptions.

In Java, exception objects are all instances derived from the Throwable class. Exceptions have their own syntax and specific inheritance structure. The following figure is a schematic diagram of the exception hierarchy.

 Exceptions caused by program errors belong to RuntimeException. Exceptions derived from RuntimeException include: incorrect type conversion, array access out of bounds, and null pointer access. Exceptions derived from the Error class or RuntimeException class are called "unchecked exceptions", and all other exceptions are called "checked exceptions". When encountering a program exception, declaring a checked exception can tell the compiler what exception may occur, and let the compiler return a value to confirm the exception.

First, throw an exception: find a suitable exception class, create an object of this class, and throw the object. For example, define a class derived from IOException. The defined class should contain two constructors, one is the default constructor; the other is a constructor with detailed description information. The toString method of the super class Throwable will print out these details.

class FileFormatException extends IOException {
        public FileFormatException(){}
        public FileFormatException(String gripe){
           
                    super (gripe);
                }
            } 


String readData(Scanner in) throws EOFException {

        while (...){
            if (!in.hasNext()) { // EOF  encountered

                if (n < len)
                    throw new EOFException();
            }
            ...
        }
        return s;
    }

The next step is to catch the exception, the compiler will print out the stack information, and the program will return to the user interface processing loop. A try/catch statement block must be set up to catch exceptions.

public void read(String filename) {
        try
        {
            InputStream in = new FileInputStream(filename);
            int b;
            while ((b = in.read() != -1) {
                process input
            }
        } catch (IOException exception) {
            exception.printStackTrace() ;
        }
    }

If any code in the try block throws an exception class specified in the catch clause, then:
1) The program will skip the rest of the try block code.
2) The program will execute the processor code in the catch clause.
If the code in the try statement block does not throw any exception, the program will skip the catch clause. If any code in the method throws an exception type that is not declared in the catch clause, then the method will exit immediately (hopefully the caller has designed a catch clause for this type of exception).

Multiple exception types can be captured in a try statement block, and different types of exceptions can be handled differently. You can 
use a separate catch clause for each exception type as follows:

try 
{
code that might throw exceptions
}catch (FileNotFoundException e){
emergency actionfor missingfiles 
}catch (UnknownHostException e){
emergency action for unknown hosts
}catch (IOException e){
emergency actionfor all other I/O problems
}

Catching multiple exceptions makes the code look simpler and more efficient. The generated bytecode contains only one code block corresponding to the public catch clause. Exception objects may contain information about the exception itself. If you want to get more information about the object, you can use e.getMessage(), or use e.getClass().getName() to get more detailed error information.

Guess you like

Origin blog.csdn.net/m0_72000264/article/details/129851406