preface

Summary of Java exceptions ten key knowledge points, interview or work useful oh, come on.

What is an exception

An exception is a problem that prevents the current method or scope from continuing to execute. For example, the file you read does not exist, the array is out of bounds, the divisor is 0 when you do a division, and so on.

An exception where the file could not be found:

public class TestException {
    public static void main(String[] args) throws IOException {
        InputStream is = new FileInputStream("jaywei.txt");
        int b;
        while((b = is.read()) ! = -1) {}}}Copy the code

Running results:

Exception in thread "main"Java. IO. FileNotFoundException: jaywei. TXT (system could not find the file specified. at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.<init>(FileInputStream.java:138) at java.io.FileInputStream.<init>(FileInputStream.java:93) at exception.TestException.main(TestException.java:10)Copy the code

2. Hierarchy of exceptions

Once upon a time, there was an old man named Throwable who had two sons. The first son was named Error and the second was named Exception.

Error

Indicates compile-time or system errors, such as virtual machine-related errors, OutofMemoryErrors, etc. Errors cannot be handled.

Exception

Code exceptions, the base type Java programmers care about is usually Exception. It can be handled by the program itself, which is what distinguishes it from Error.

It can be divided into RuntimeException (RuntimeException) and CheckedException (checkable exception).

Common RuntimeException exceptions:

- NullPointerException null-pointer exception - ArithmeticException Throw this exception - IndexOutOfBoundsException array index cross-border exception - a ClassNotFoundException couldn't find a class - IllegalArgumentException parameters (illegal)Copy the code

Common Checked exceptions:

- IOException (exceptions that may occur when operating on input and output streams) - ClassCastException(Type conversion exception class)Copy the code
  • Checked Exceptions are exceptions that the compiler says you must handle.
  • On the other hand, Unchecked Exceptions, which the compiler is not required to enforce, include Error and RuntimeException and their subclasses.

Three, exception handling

When an exception occurs, an exception object is created on the heap. The current execution path is terminated, and a reference to the exception object is ejected from the current environment. At this time the exception handler, so that the program from the error state to recover, so that the program continues to run.

Exception processing includes throwing exceptions, catching exceptions, and declaring exceptions. As shown in figure:

Catch exceptions

Try {// program code}catch(Exception e){// catch block}finaly{// Code block that will execute anyway}Copy the code

We can try… catch… Catch the exception code, and finaly performs the final actions, such as closing the stream.

Declare to throw an exception

In addition to try… catch… To catch exceptions, we can also declare throwing exceptions through throws.

When you define a method, you can declare it with the throws keyword. The use of the throws keyword indicates that the method does not handle exceptions, leaving them to its caller. Do you think they are irresponsible?

Haha, let’s see the demo

// This method declares an I/O exception with throws. private voidreadFile() throws IOException {
        InputStream is = new FileInputStream("jaywei.txt");
        int b;
        while((b = is.read()) ! = -1) {}}Copy the code

Any exception declared thrown from a method must use the throws clause.

An exception is thrown

The throw keyword throws an exception of type Throwable, which occurs in the body of a function. In exception handling, the try statement captures an exception object that can be thrown itself.

For example, throw an exception object of the RuntimeException class:

throw new RuntimeException(e);
Copy the code

Any Java code can throw an exception through a Java throw statement.

Pay attention to the point

  • Non-checking exceptions (Error, RuntimeException, or their subclasses) may not be declared to throw using the throws keyword.
  • If a method has a compile-time exception, try-catch/ throws is required. Otherwise, a compilation error occurs.

Try-catch-final-return execution sequence

Try-catch-final-return Indicates the execution description

  • If no exception occurs, the catch part is not executed.
  • Finally executes whether or not an exception occurs.
  • Finally is executed even when there is a return ina try and catch
  • Finally is executed after the expression following the return has been evaluated. If there is no return in finally, the return value will remain the same regardless of the code in finally. In this case, the return value of the function is determined before finally is executed.
  • Finally, do not return. Otherwise, you will not be able to return a try or catch.

Let’s look at an example

 public static void main(String[] args) throws IOException {
        System.out.println("The result:" + test());
    }

    private static int test() {
        int temp = 1;
        try {
            System.out.println("start execute try,temp is:"+temp);
            return ++temp;
        } catch (Exception e) {
            System.out.println("start execute catch temp is: "+temp);
            return ++temp;
        } finally {
            System.out.println("start execute finally,temp is:"+ temp); ++temp; }}Copy the code

Running results:

start execute try,temp is:1
start execute finally,temp is:2
result:2
Copy the code

Analysis of the

  • First execute the try section, print the log, and execute++tempThe expression temp changes to 2 and the value is saved.
  • Because no exception occurred, the catch block was skipped.
  • Execute the finally code block, print the log, and execute++tempExpression.
  • Returns the value 2 saved in the try section.

Five, Java exception class several important methods

Take a quick look at all the methods of the exception class, as shown below:

getMessage

Returns the detail message string of this throwable.
Copy the code

GetMessage returns the detailMessage property of the Throwable, which in turn represents a detailed message description of the exception.

For example, the detailMessage contains the name of the missing file when a FileNotFoundException occurs.

getLocalizedMessage

Creates a localized description of this throwable.Subclasses may override this
method in order to produce alocale-specific message. For subclasses that do not
override thismethod, the default implementation returns the same result
as getMessage()
Copy the code

Localized description of Throwable. Subclasses can override this method to generate locale-specific messages. For subclasses that do not override this method, the default implementation returns the same result getMessage().

getCause

Returns the cause of this throwable or null if thecause is nonexistent or unknown.
Copy the code

Returns the cause of this throwable event, or null if the cause does not exist or is unknown.

printStackTrace

Prints this throwable and its backtrace to thestandard error stream. The first line of output contains the result of the  toString() methodfor
this object.Remaining lines represent data previously recorded by the 
method fillInStackTrace(). 
Copy the code

This method prints stack trace information to the standard error stream.

The first line of output contains the result of this object’s toString() method. The remaining lines represent the data previously recorded by the method fillInStackTrace(). Here’s an example:

 java.lang.NullPointerException
         at MyClass.mash(MyClass.java:9)
         at MyClass.crunch(MyClass.java:6)
         at MyClass.main(MyClass.java:3)
Copy the code

Custom exceptions

A custom Exception is usually defined as a subclass that inherits from the Exception class.

So why custom exceptions?

  • The exception architecture provided by Java cannot anticipate all errors.
  • In business development, using custom exceptions makes project code more standardized and easier to manage.

Below is a simple demo of our custom exception class

Public class BizException extends Exception {private String message; // errorCode private String errorCode; publicBizException() {
    }

    public BizException(String message, String errorCode) {
        this.message = message;
        this.errorCode = errorCode;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) { this.errorCode = errorCode; }}Copy the code

Run the Main square to test it


public class TestBizException {

    public static void testBizException() throws BizException {
        System.out.println("throwing BizException from testBizException()");
        throw new BizException("100"."Dude, I was wrong.");
    }

    public static void main(String[] args) {
        try {
            testBizException();
        } catch (BizException e) {
            System.out.println("Self-defined exception"); e.printStackTrace(); }}}Copy the code

Running results:

exception.BizException: 100
throwing BizException from testBizException () your custom exception at exception. TestBizException. TestBizException ats (TestBizException. Java: 7) exception.TestBizException.main(TestBizException.java:12)Copy the code

Java7 new try-with-resources statement

Try-with-resources, a new feature in Java7, is used for automatic resource management.

  • Resources are objects that must be closed when the program is used up.
  • Try-with-resources ensures that each declared resource is closed at the end of the statement
  • What objects can be used as resources? Objects that implement either the Java.lang. AutoCloseable interface or the java.io.Closeable interface are OK.

intry-with-resourcesBefore the advent of

try{
    //open resources like File, Database connection, Sockets etc
} catch (FileNotFoundException e) {
    // Exception handling like FileNotFoundException, IOException etc
}finally{
    // close resources
}
Copy the code

Java 7,try-with-resourcesOnce present, use the resource implementation

try(// open resources here){
    // use resources
} catch (FileNotFoundException e) {
    // exception handling
}
// resources are closed as soon as try-catch block is executed.
Copy the code

Java7 uses the resource demo

public class Java7TryResourceTest {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader(
                "C:/jaywei.txt"))) { System.out.println(br.readLine()); } catch (IOException e) { e.printStackTrace(); }}}Copy the code

Using thetry-with-resourcesThe benefits of

  • The code is more elegant and has fewer lines.
  • Resources are managed automatically without worrying about memory leaks.

Abnormal chain

It is often tempting to throw an exception after catching one, and to save information about the original exception. This is called an exception chain.

Throw throws a new exception, which causes the original exception information to be lost. Prior to JDk1.4, programmers had to write their own code to save the raw exception information. All Throwable subclasses now accept a cause object as an argument in the constructor.

This cause is used to indicate the original exception, so that by passing the original exception to the new exception, even if a new exception is created and thrown at the current location, the exception chain can be traced back to where the exception originally occurred.

The usage is as follows:

public class TestChainException {

    public void readFile() throws MyException{
        try {
            InputStream is = new FileInputStream("jay.txt");
            Scanner in = new Scanner(is);
            while(in.hasNext()) { System.out.println(in.next()); }} catch (FileNotFoundException e) {throw new MyException("Where are the files?", e);
        }
    }

    public void invokeReadFile() throws MyException{
        try {
            readFile(); } catch (MyException e) {throw new MyException("File not found", e); } } public static void main(String[] args) { TestChainException t = new TestChainException(); try { t.invokeReadFile(); } catch (MyException e) { e.printStackTrace(); Public MyException(String message, Throwable cause) {super(message, cause); }Copy the code

Running results:

We can see that the exception message is saved. If cause (e) is removed, look at the result:

It can be found that without Throwable cause, the original exception information disappeared.

9. Exception matching

When an exception is thrown, the exception handling system finds the “most recent” handler in the order in which the code was written. Once it finds a matching handler, it assumes that the exception will be handled and stops looking.

Lookup does not require that the exception thrown be an exact match to the handler’s exception. Objects of derived classes can also be equipped with handlers for their base classes

Look at the demo

package exceptions; / / : exceptions/Human.java // Catching exception hierarchies. class Annoyance extends Exception {} class Sneeze extends Annoyance {} public class Human { public static void main(String[] args) { // Catch the exacttype:
    try {
      throw new Sneeze();
    } catch(Sneeze s) {
      System.out.println("Caught Sneeze");
    } catch(Annoyance a) {
      System.out.println("Caught Annoyance");
    }
    // Catch the base type:
    try {
      throw new Sneeze();
    } catch(Annoyance a) {
      System.out.println("Caught Annoyance"); }}}Copy the code

Running results:

Catch (Side A) catches side and all exceptions derived from it. By catching the exception of the base class, you can match the exception of all derived classes

try { throw new Sneeze(); } catch(side A) {} catch(side S) {// This line the compiler will error as the exception is handled by the previous catch clause}Copy the code

Java common exceptions

NullPointerException

Null-pointer exception, the most common exception class. In short, this exception is generated when an uninitialized object or non-existent object is called.

ArithmeticException

Arithmetic exception class. An exception occurs when the divisor is 0.

ClassCastException

A cast exception, which is a runtime exception thrown by the JVM when it detects an incompatibility between casts of two types.

ArrayIndexOutOfBoundsException

Array subscript out of bounds exception, when dealing with arrays, need to be aware of this exception.

FileNotFoundException

If the file to be read or written cannot be found, the exception occurs.

SQLException

Operation database Exception, which is Checked Exception;

IOException

IO exceptions, usually related to reading and writing files, are also Checked exceptions. Read and write files at ordinary times, remember IO stream closed!

NoSuchMethodException

Method found no exception

NumberFormatException

String conversion to numeric exception

conclusion

This summary has a unique way to end with a few classic abnormal interview questions, to help you review, hee hee.

  • What are the types and characteristics of Java exceptions? (2)
  • What are exceptions in Java? (1)
  • What is the difference between Error and exception? (2)
  • What is an exception chain? (8 points can be answered)
  • Try-catch-final-return execution sequence
  • List some common runexceptions.
  • What are the important methods of Java exception classes? (5 points can be answered)
  • Error and Exception, CheckedException, RuntimeException. (2)
  • List five runtime exceptions. (2)
  • New try-with-resources statements in Java 7
  • How do I customize exceptions? (6 points can be answered)
  • Explain the common exceptions and why they occur.
  • Talk about exception matching
  • Talk about exception handling

Personal public account

  • If you are a good boy who loves learning, you can follow my public account and study and discuss with me.
  • If you feel that this article is not correct, you can comment, you can also follow my public account, private chat me, we learn and progress together.