Java exception classes and custom exceptions

table of Contents

 

 Exception class

Exception class hierarchy

throws/throw keywords:

throws:

throw:

try catch finally statement

Declare a custom exception


 Exception class

There are three main reasons for an exception in Java:

  1. An exception occurred in a Java internal error, an exception generated by the Java virtual machine.

  2. Exceptions caused by errors in the written program code, such as null pointer exceptions, array out-of-bounds exceptions, etc.

  3. The exception manually generated by the throw statement is generally used to inform the caller of the method some necessary information.

There are many reasons for the abnormality, usually including the following categories:

  • The user entered illegal data.
  • The file to be opened does not exist.
  • The connection was interrupted during network communication, or the JVM memory overflowed.

Some of these exceptions are caused by user errors, some are caused by program errors, and others are caused by physical errors.

Java handles exceptions through an object-oriented approach. During the operation of a method, if an exception occurs, the method will generate an object representing the exception and hand it over to the runtime system. The runtime system looks for the corresponding code to handle the exception.

 

We call the process of generating an exception object and submitting it to the runtime system as throwing an exception . The runtime system searches in the call stack of the method until it finds an object that can handle this type of exception. This process is called catching the exception.

To understand how Java exception handling works, you need to master the following three types of exceptions:

  • Checked exceptions: The most representative checked exceptions are those caused by user errors or problems, which cannot be foreseen by programmers. For example, when opening a file that does not exist, an exception occurs. These exceptions cannot be simply ignored during compilation.
  • Runtime exceptions:  Runtime exceptions are exceptions that may be avoided by programmers. Contrary to checked exceptions, runtime exceptions can be ignored at compile time.
  • Error: An  error is not an exception, but a problem beyond the control of the programmer. Errors are usually ignored in the code. For example, when the stack overflows, an error occurs, and they cannot be checked during compilation.

 

Exception class hierarchy

All exception classes are subclasses inherited from java.lang.Exception class.

The Exception class is a subclass of the Throwable class. In addition to the Exception class, Throwable also has a subclass Error.

Java programs usually do not catch errors. Errors generally occur when serious failures occur, and they are outside the scope of the Java program.

Error is used to indicate an error occurred in the runtime environment.

For example, JVM memory overflow. Generally, the program will not recover from errors.

The exception class has two main subclasses: IOException class and RuntimeException class.

 

 

 

Exception method

The following list is the main methods of the Throwable class:

 

  • printStackTrace() method: Point out the type, nature, stack level and location of the exception in the program (for the use of the printStackTrace method, please refer to the section " Java Exception Trace Stack ").
  • getMessage() method: output the nature of the error.
  • toString() method: gives the type and nature of the exception.

Java also defines some other exceptions according to each class library. The following table lists Java's unchecked exceptions.

abnormal

description

ArithmeticException

When an abnormal operation condition occurs, this exception is thrown. For example, when an integer is "divided by zero", an instance of this class is thrown.

ArrayIndexOutOfBoundsException

The exception thrown when accessing an array with an illegal index. If the index is negative or greater than or equal to the size of the array, the index is illegal.

ArrayStoreException

An exception thrown when trying to store an object of the wrong type in an object array.

ClassCastException

This exception is thrown when trying to cast the object to a subclass that is not an instance.

IllegalArgumentException

The thrown exception indicates that an illegal or incorrect parameter was passed to the method.

IllegalMonitorStateException

The thrown exception indicates that a thread has tried to wait for the monitor of the object, or tried to notify other monitors that are waiting for the object without specifying a monitor.

IllegalStateException

A signal generated when a method is called at an illegal or inappropriate time. In other words, the Java environment or Java application is not in the proper state required by the requested operation.

IllegalThreadStateException

The exception thrown when the thread is not in the proper state required by the requested operation.

IndexOutOfBoundsException

Indicates that a sort index (such as sorting an array, string, or vector) is out of range.

NegativeArraySizeException

If the application attempts to create an array with a negative size, this exception is thrown.

NullPointerException

This exception is thrown when the application tries to use null where the object is needed

NumberFormatException

This exception is thrown when the application attempts to convert a string into a numeric type, but the string cannot be converted into an appropriate format.

SecurityException

An exception thrown by the security manager, indicating a security violation.

StringIndexOutOfBoundsException

This exception is thrown by the String method, indicating that the index is either negative or exceeds the size of the string.

UnsupportedOperationException

When the requested operation is not supported, this exception is thrown.

The following table lists the checked exception classes defined by Java in the java.lang package.

abnormal

description

ClassNotFoundException

When the application tried to load the class, the corresponding class could not be found and the exception was thrown.

CloneNotSupportedException

When the clone method in the Object class is called to clone an object, but the object's class cannot implement the Cloneable interface, this exception is thrown.

IllegalAccessException

This exception is thrown when access to a class is denied.

InstantiationException

When trying to use the newInstance method in the Class class to create an instance of a class, and the specified class object cannot be instantiated because it is an interface or an abstract class, this exception is thrown.

InterruptedException

A thread was interrupted by another thread and the exception was thrown.

NoSuchFieldException

The requested variable does not exist

NoSuchMethodException

The requested method does not exist

throws/throw keywords:

throws:

Used to declare exceptions that may occur, for example, if a method does not want to have any exception handling (generating an exception that it does not handle), then when there is no code for exception handling, the method must be declared as possible All exceptions in order to pass the exception to the outside of the method for processing. The method of using the throws statement means that this method does not handle exceptions (in fact, if you don't want to handle it by yourself, then let someone else, tell them what exceptions will occur, report your own fault, and let others handle it). The format is: method name (parameter) throws exception class 1, exception class 2, .....

Note: When a method is declared, you can use the throws keyword to declare several exceptions to be generated, and specify the operation that generates the exception in the method body of the method, that is, create an object with the relevant exception class and use the throw keyword Throw the exception object, causing the method to end execution.

The idea of ​​using throws to declare exceptions is: The current method does not know how to handle this type of exception, and the exception should be handled by the caller at the upper level; if the main method does not know how to handle this type of exception, it can also Use the throws statement to throw an exception, and the exception will be handed over to the JVM for processing. The JVM handles exceptions by printing the stack trace of the exception and suspending the program. This is why the previous program automatically ends after encountering an exception.

throw:

When the throw statement is executed, the statements following it will not be executed. At this time, the program turns to the caller program, looks for a matching catch statement, and executes the corresponding exception handler. If no matching catch statement is found, then go to the calling program of the previous layer. This way, layer by layer, until the outermost exception handler terminates the program and prints out the call stack.

try catch finally statement

The try catch statement is used to catch and handle exceptions, the finally statement is used to code that must be executed under any circumstances (except for special cases), the throw statement is used to throw exceptions, and the throws statement is used to declare exceptions that may occur.

try {
    // 可能发生异常的语句
} catch(ExceptionType e) {
    // 处理异常语句
}

In the above grammar, the statement that may cause an exception is encapsulated in a try statement block to catch the possible exception. Put the matched exception class in the () after the catch to indicate the exception type that the catch statement can handle. When an exception occurs, an instantiated object of the exception class is generated.

 

If an exception occurs in the try statement block, a corresponding exception object will be thrown, and then the catch statement will be captured and processed according to the type of the thrown exception object. After processing, the program will skip the remaining statements in the try block and switch to the first statement after the catch block to start execution.

 

If no exception occurs in the try block, the try block ends normally, the subsequent catch block is skipped, and the program will start execution from the first statement after the catch block.

 

Note: try...catch is different from if...else . The curly brace {} after try cannot be omitted , even if there is only one line of code in the try block, the curly brace cannot be omitted. Similarly, the curly braces {} after the catch block cannot be omitted. In addition, the variable declared in the try block is only a local variable in the code block. It is only valid in the try block, and the variable cannot be accessed elsewhere.

 

 

Note the following points when using try-catch-finally statements:

  1. Only the try block is necessary in the exception handling syntax structure, that is, if there is no try block, there can be no catch block and finally block;
  2. Both the catch block and the finally block are optional, but at least one of the catch block and the finally block can appear, or they can appear at the same time;
  3. There can be multiple catch blocks, and the catch block that catches the exception of the parent class must be behind the exception of the catch subclass;
  4. There cannot be only a try block, neither a catch block nor a finally block;
  5. Multiple catch blocks must be located after the try block, and the finally block must be located after all catch blocks.
  6. The syntax format of finally matches the try statement block, this kind of situation will cause the exception to be lost, so it is not common.

 

Under normal circumstances, regardless of whether an exception is thrown, the statements in the finally block will be executed . The execution flow is shown in Figure 1.

 

                                        Figure 1 Flow chart of try catch finally statement execution

 

The execution of try catch finally block can be subdivided into the following three situations:

  1. If no exception is thrown in the try code block, execute the finally code block directly after the try code block is executed, and then execute the statement after the try catch finally block.
  2. If an exception is thrown in the try code block and caught by the catch clause, the execution of the try code block is terminated where the exception is thrown, the matching catch code block is executed instead, and the finally code block is executed. If no exception is thrown in the finally code block, the execution of the statement after the try catch finally block is continued; if an exception is thrown in the finally code block, the exception is passed to the caller of the method.
  3. If the exception thrown in the try code block is not caught by any catch clause, then the statement in the finally code block will be executed directly and the exception will be passed to the caller of the method.

 

Unless the method System.exit(int status) is called to exit the virtual machine in the try block or the catch block, no matter what code is executed in the try block or the catch block, what happens, the finally block of exception handling will always be executed .

 public class test1 {
      public static String output="";
      public static void foo(int i) {
          try {
              
          } catch (Exception e) {
              // TODO: handle exception
          }finally {
              
         }
         try {
             if(i==1) throw new  Exception("i不能为1");
             output+="A";            
         } catch (Exception e) {
             System.out.println(e.getMessage());
             output+="M";
             return;
         }finally {
             output+="C";            
         }
         output+="G";
         
     }
     public static void main(String[] args) {
         foo(0);
         foo(1);
         System.out.println(output);
     }
     
 }

The result is:

i cannot be 1

ACGMC

 

 

public class ZIDemo
{
    public static void main(String[] args)
    {
        try
        {
            //调用带throws声明的方法,必须显式捕获该异常
            //否则,必须在main方法中再次声明抛出
            throwChecked(-3);
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
        //调用抛出Runtime异常的方法既可以显式捕获该异常,
        //也可不理会该异常
        throwRuntime(3);
    }
    public static void throwChecked(int a)throws Exception
    {
        if (a > 0)
        {
            //自行抛出Exception异常
            //该代码必须处于try块里,或处于带throws声明的方法中
            throw new Exception("a的值大于0,不符合要求");
        }
    }
    public static void throwRuntime(int a)
    {
        if (a > 0)
        {
            //自行抛出RuntimeException异常,既可以显式捕获该异常
            //也可完全不理会该异常,把该异常交给该方法调用者处理
            throw new RuntimeException("a的值大于0,不符合要求");
        }
    }
}

 

Declare a custom exception

You can customize exceptions in Java. The following points need to be kept in mind when writing your own exception class.

  • All exceptions must be a subclass of Throwable.
  • If you want to write a checked exception class, you need to inherit the Exception class.
  • If you want to write a runtime exception class, you need to inherit the RuntimeException class.

You can define your own exception class as follows:

class MyException extends Exception{ }

The exception class created by only inheriting the Exception class is a checked exception class.

An exception class, like any other class, contains variables and methods

In the coding standard, the class name of the custom exception class is generally named XXXException , where XXX is used to represent the function of the exception.

 

 

 

 

 

Guess you like

Origin blog.csdn.net/q1246192888/article/details/106963128