An overview of the exception handling framework and its benefits

The best way to catch errors is during compilation, preferably before you try to run the program. However, not all errors can be detected at compile time, and some problems must always be discovered and resolved at run time. A good exception framework is responsible for providing a way for the error producer to communicate some relevant information to the receiver so that it can know the cause of the problem and then handle it properly.

One benefit of using an exception-handling framework is that it tends to reduce the complexity of error-handling code, separating exception-handling code from normal business code, ensuring more elegant code, and improving program robustness. If you don’t use exception handling, you have to check for specific errors and handle them in many places in your program. If you use exceptions, you don’t need to check at the method call because the exception mechanism ensures that the error is caught. See the following pseudo-code to achieve the copy function:

Public static void main(String[] args) {if("d://a. }else{// copyFile copyFile(); }}else{system.out.println (" space is insufficient "); }}else{system.out.println (" file does not exist "); }}Copy the code

Look at this pseudo-code, the purpose is to copy the file to disk E, because there is no exception, so there is a lot of conditional judgment, and it is a mixture of logic code and error handling code.

How do you use exceptions?

Try {// copyFile copyFile(); }catch (Exception e) { e.printStackTrace(); }Copy the code

This approach not only saves code, but also separates code that describes what to do during normal execution from code that says what goes wrong. In summary, the exception mechanism makes reading, writing, and debugging code much more orderly than previous error-handling methods.

How to handle exceptions

Java handles exceptions as objects. When executing a method, if an exception occurs, the method generates an object representing the exception, stops the current execution path, and presents the exception object to the Java Runtime Environment (JRE). After the JRE obtains the exception, Find the appropriate code to handle the exception. The JRE looks through the method call stack, tracing back from the method that generated the exception until it finds the corresponding exception-handling code.

Architecture of exceptions

Java defines a Throwable class as a superclass for all exception classes. There are many Exception classes defined in Java, divided into two main classes: Error and Exception

  • Error: An error occurs when there are insufficient resources, constraints fail, or a condition occurs that other programs cannot continue running. These errors cannot be fixed by the program itself, and are serious problems. Most of these errors are not related to what the code writer is doing, but represent problems that occur in the JVM while the code is running, such as OutofMemoryErrors, StackOverflowErrors, and so on. Error indicates that the system JVM is in an unrecoverable crash state.
  • Exception: Exceptions that can be handled by the program itself, such as null Pointers, out-of-bounds subscripts, type conversions, etc. Exception is the superclass of all Exception classes, and its subclasses correspond to the various possible Exception events, which can be divided into:
    • Runtime exception: RuntimeException: these abnormalities are usually caused by programming errors, so when writing programs, does not require must use the exception handling mechanism to deal with this kind of unusual, but often need to by adding “logical processing to avoid these exceptions,” common run-time exceptions are: an array subscript bounds, null Pointers, by 0, etc

    • Check for exceptions: CheckedException: All exceptions that are not RuntimeExceptions are called CheckedException, which forces the programmer to handle exceptions and makes the program much more reliable. Exceptions such as IoException, SQLException, and user-defined exceptions must be handled at compile time, otherwise they will not be compiled.

int a = 0; // RuntimeException can be logically determined to avoid exceptions if(a! =0){ a = 10/a; } String str = null; // Avoid runtimeexceptions by logical judgment if(STR! =null && ! str.equals("")){ System.out.println(str.length()); }Copy the code
// Check the error: IoException must wrap a try/catch or throw an exception try {FileOutputStream FileOutputStream = new FileOutputStream(new File("d://a.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); }Copy the code

The difference between Error and Exception

An Error is usually a catastrophic and fatal Error that a program cannot control or handle. When these exceptions occur, the Java Virtual Machine (JVM) usually chooses to terminate the thread.

Exceptions are usually handled by programs, and should be handled as much as possible in programs.

Check exceptions are exceptions that must be handled. When such exceptions occur in the program, you can either catch them using a try/catch or throw them upwards using a throws statement. Otherwise, the compilation fails.

Unchecked exceptions include runtime exceptions and errors, which the compiler does not enforce, but which should be taken into account when writing code.

Exception handling keyword

  • Try: used for listening. A try statement is followed by a block of code enclosed in curly braces (curly braces cannot be omitted), called a try block for short. It contains code that might throw an exception. When an exception occurs within the try block, the exception is thrown.
  • Catch: Used to catch exceptions. The catch corresponds to the exception type and a code block that handles the exception of the corresponding type generated by the try block.
  • Throws: Used in a method signature to declare exceptions that the method may throw.
  • Throw: Used to throw an exception
  • Finally: Used to clean up resources, finally blocks are always executed. Multiple catch blocks can be followed by a finally block, which is used to reclaim physical resources (such as database connections, network connections, and disk files) that are opened ina try block. A return or throw statement ina try or catch block is executed only after the finally block is complete. If a statement terminating a method, such as a return or throw, is used in the finally block, then execution is stopped.

Finally, a comprehensive use case is attached

public static void main(String[] args) { FileReader reader = null; Try {try/catch reader = new FileReader("d:/b.txt"); Catch char read = (char) reader.read(); System.out.println(read); //FileNotFoundException is a subclass of IOException} catch (FileNotFoundException e) {e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); Close} finally {try {reader.close(); } catch (IOException e) { e.printStackTrace(); }}}Copy the code

Or throw with throws