“This is the 14th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

preface

I believe that friends in the process of writing code have more or less encountered a variety of exceptions, so do you know what are the exceptions? Here’s a review of exceptions in Java.

What is an exception

Exceptions are errors in the programs we develop, but not all errors are exceptions, and errors can sometimes be avoided. Exceptions are objects in object-oriented programming languages such as Java.

There are also a lot of exceptions, including the user input illegal characters, in the program without verification, there will be abnormal parameters; When the program runs, there is a divisor 0 variable, there will be exceptions; If you open a file in a path that does not exist, an exception message is displayed. So how do we deal with different exceptions? What exceptions do I need to keep running and what exceptions do I need to stop running? This is where we need to pay attention as we write and develop business logic.

Checking-time exception: checking-time exception refers to the exception during lexical, syntax, statement, and dependency compilation of the program during compilation. The programmer cannot foresee the exception and the exception is prompted during compilation. For example, the dependency file is missing.

Runtime exception: Runtime exception refers to the abnormality that occurs in the program running stage after compilation. This kind of anomaly appears more often when I just enter the developer. This kind of runtime exception can be avoided by the programmer’s code writing. For example, null pointer exception,

Error: A serious exception that is usually ignored in code, such as memory overflow. Errors are not detected during compilation.

Exceptions in Java

The author is a Java developer, so based on the Exceptions in Java made a simple summary. The following figure is based on some exception information listed in javaJDK.

graph TD
Throwable --> Error
Throwable --> Exception
Exception --> IOException
Exception --> RuntimeException
Exception --> BeansException
Exception --> IIOException
Exception --> ....
Error  --> NoSuchClassError
Error  --> ClassFormatError
Error  --> IOError
Error  --> ...

Throwable is a superclass of Error and Exception. All Exception classes are subclasses of Exception, and all errors are subclasses of Error. When an exception occurs in our program, we need to act on different exceptions. The basic methods in Throwable class are introduced briefly.

getMessage()

The getMessage() method returns detailed information about the exception that occurred. The message is initialized in the constructor of the Throwable class. In our program, we can directly obtain Exception E through the Exception information as follows:

e.getMessage();
Copy the code

getCause()

GetCause () returns a Throwable object representing the cause of the exception.

toString()

The toString() method returns the string name of the class using the result of getMessage().

printStackTrace()

The printStackTrace() method prints the toString() result and stack hierarchy to System.err, the error output stream. You typically use printStackTrace() to print the exception log to the console.

getStackTrace()

The getStackTrace() method returns an array containing the stack hierarchy. The element with subscript 0 represents the top of the stack, and the last element represents the bottom of the method call stack.

Exception handling

Since there are so many exceptions in our development program, how do we catch these exceptions and handle them, so as to reduce unnecessary errors, so now we begin to introduce.

throws/throw

The throws/throw keyword is used to declare a method that does not catch a checking exception. The simple format is as follows: Usually used at the end of a method.

    public void testException() throws Exception{
        
    }
Copy the code

You can also throw an exception using the throw keyword. Throws thrown using the throw keyword are accepted with a keyword declaration exception followed by the method name.

  public void testException() throws Exception{
        throw  new Exception();
    }
Copy the code

Try/catch the key words

In our program, we can use the try and catch keywords to catch exceptions for blocks of code that might occur. Try /catch blocks are placed where exceptions can occur. The code in the try/catch code block is called the protected code. When an exception occurs in the protected code, it can execute the subsequent code according to business needs or process the exception information and throw the exception. This is a flexible exception handling method, and the code block format is as follows:

try{
   // Business code
}catch(Exception e){
   / / Catch block
}
Copy the code

Of course, multiple catches within the try/catch keyword are also possible, called multiple catches. Its common format is as follows:

try{
   // Business code
}catch(Exception type1 e1){
  // Business code
}catch(Exception type2 e2){
  // Business code
}catch(Exception type3 e3){
  // Business code
}
Copy the code

In the case of an exception, the code in a try matches the contents of the first catch block first, from near to far, until the relevant exception is matched.

Finally the keyword

The finally keyword is created at the end of a try/catch block. Code ina finally block is always executed regardless of whether or not a try/catch block has an exception. In the finally code block, you can run statements of the cleanup nature, such as cleanup types. The syntax is as follows:


try{
   // Business code
}catch(Exception e){
   / / Catch block
}finally{
    // Business code
}
Copy the code

conclusion

Ok, the above is Java exception types and their summary, thank you for reading, I hope you like, if it is helpful to you, welcome to like collection. If there are shortcomings, welcome comments and corrections. See you next time.

About the author: [Little Ajie] a love tinkering with the program ape, JAVA developers and enthusiasts. Public number [Java full stack architect] maintainer, welcome to pay attention to reading communication.