Home >Java >javaTutorial >What is an exception in java?

What is an exception in java?

青灯夜游
青灯夜游Original
2019-11-16 17:23:492863browse

What is an exception in java?

What is an exception?

It is a basic philosophy of Java that poorly structured code cannot run.

The ideal time to find errors is during compilation. However, the compiler cannot find all errors, and the remaining problems need to be solved while the program is running. This requires that the error can pass appropriate information to a specific recipient for processing in some way.

The purpose of exception handling in Java is to simplify the generation of large, reliable programs by using a small amount of code. In this way, there are no unhandled errors in your application, and it also brings a Obvious benefit: reduced complexity of error handling code.

Abnormal, according to the literal meaning, means unexpected. To understand it at the code level, it prevents the current method or scope from continuing to execute. Exceptions are events that cause a program to fail to function in its intended execution. There are three types of exceptions - checked exceptions, errors and runtime exceptions.

In Java, exceptions are treated as objects, and their base class is Throwable.

Exception types in Java

Java derives Exception and Error directly from Throwable. Among them, Exception is the basic type that can be thrown. Exception-type exceptions may be thrown in Java class libraries, methods, and runtime failures. Exception represents a recoverable exception, which can be caught by the compiler; Error represents a compile-time and system error, indicating that a serious error occurred during the running of the system, which is an unrecoverable error. Since this is a serious error at the JVM level, so This error causes the program to terminate execution. Exceptions are divided into checked exceptions and runtime exceptions.

The structural hierarchy diagram of the exception class is as follows:

What is an exception in java?

Typical RuntimeException (runtime exception) includes NullPointerException, ClassCastException (type conversion exception), IndexOutOfBoundsException (out-of-bounds exception) Exception), IllegalArgumentException (illegal parameter exception), ArrayStoreException (array storage exception), AruthmeticException (arithmetic exception), BufferOverflowException (buffer overflow exception), etc.;

What is an exception in java?

Non-RuntimeException( Checked exceptions) include IOException, SQLException, InterruptedException (interrupted exception - when the calling thread sleeps), NumberFormatException (number formatting exception), etc.

According to the compiler checking method, exceptions can be divided into checked exceptions (CheckedException) and unchecked exceptions (UncheckedException). The combination of Error and RuntimeException is called UncheckedException. It is so called because the compiler does not check whether the method handles or throws these two types of exceptions. Therefore, no error will be reported if this type of exception occurs during compilation. The default is virtual The machine provides processing methods. Except for the two types of exceptions Error and RuntimeException, other exceptions are called Checked exceptions.

What is an exception in java?

How Java handles exceptions

1. try-catch, try-finally, try-catch-finally

For checked type exceptions, we must either handle it or use throws in the method header.

public static void createFile() throws IOException{
    File file = new File("C:/test.txt");
    if(!file.exists()){
            file.createNewFile();
    }
}
public static void main(String[] args) {
    try {
        createFile();
    } catch (IOException ex) {
        // handle exception here
    }
}

A few points to note about catch:

1). The exception type of the parameter must be the Throwable class or its subclass.

2) For catch statements from top to bottom, the parameter types must be in order from subclass to parent class, because once a type is matched, subsequent catches will be ignored. For example, IOException must be placed before Exception, otherwise the compiler will report an error.

3), there can be one or more catch statements, even if there is a finally statement, there can be no catch statement, such as try-finally.

If you want to catch multiple exceptions, you can use multiple catch statements. JDK7 and later will provide another way: multi-catch.

try{
    // other code
} catch (IOException | SQLException ex) {
    throw ex;  
}

4). Don’t ignore exceptions. An empty catch block will defeat the purpose of the exception, except when closing the FileInputStream, because you have not changed the state of the file, so you do not have to perform any recovery actions, and the required information has been read from the file. , so there is no need to terminate ongoing operations.

A few points to note about finally:

1). The code in finally will always be executed unless the virtual machine exits when a try or catch statement is executed (System.exit(1 )).

2). The finally block can do some resource cleanup work, such as closing files, closing cursors, etc.

3), finally block is not necessary.

In addition, if the return statement is executed in both the try and finally blocks, the final return value will be the return value in finally.

2. Exception chain

常常想要在捕获一个异常后抛出另外一个异常,并且希望把原始异常信息保存下来,这就是异常链。在JDK1.4以后,Throwable子类在构造器 中可以接受一个cause对象作为参数,表示原始异常,通过这样把原始异常传递给新的异常,使得即使在当前位置创建并抛出了新的异常,也能通过这个异常链 追踪到异常最初发生的位置。

但在Throwable子类中,只有Error, Exception, RuntimeException三类异常类提供了带cause参数的构造器,其它类型的异常则需要通过initCause()方法。例如定义了CustomException类,可以这样使用:

CustomException cmex = new CustomException();
cmex.initCause(new NullPointerException);
throw cmex;

这样一来,CustomException继承自Exception或RuntimeException,就属于自定义异常了。

一般来说,自定义异常的作用有以下情形:

1)、将检查型异常转换为非检查型异常。

2)、在产生异常时封装上下文信息、定义异常码、收集环境对象,有利于信息的传递。

异常使用指南

1、在知道该如何处理的情况下才捕获异常。

2、自定义异常类型,用以封装所有的检查型异常。

3、在程序的边界进行异常捕获。如服务端相应客户端的请求,在出口处catch内部有可能产生的异常,并统一throw一个封装过的异常给客户端,免得暴露服务端敏感信息。

4、只针对异常的情况才使用异常。不要在所有的代码中习惯性地使用try-catch,因为这会影响性能。

5、抛出与抽象相对的异常。如果方法抛出的异常与它执行的任务没有明显的联系,这种情形会使人不知所措。为了避免这个问题,更高层的实现应该捕获 低层的异常,同时抛出可以按照高层抽象进行解释的异常,这种做法被称为异常转译(exception translation),如下:

try{
    // use lower-level abstraction to do our bidding
} catch(LowerLevelException ex){
    throw new HigherLevelException(...);
}

另外一种特殊的异常转译称为异常链,上面已作描述。如果低层的异常对于调试导致高层异常的问题非常有帮助,使用异常链就很合适。高层的异常提供访问方法(Throwable.getCause)来获得低层的异常。

6、每个方法抛出的异常要有文档描述。利用Javadoc的@throws标记,记录抛出每个异常的条件。如果一个方法可能抛出多个异常,不要使 用这些异常类的某个超类。如不要声明一个方法“throws Exception”或“throws Throwable”,这将没有任何指导信息。

The above is the detailed content of What is an exception in java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What does java mean?Next article:What does java mean?