Exception rule

zhaozj2021-02-16  53

EXCEPTION

Exception exception handling is one of the important features of Java. Exception is divided into two, one is System Exception (system exception), one is Application Exception (application exception).

System Exception Inherits the RuntimeException class, does not need to be displayed or throw.

Application Exception Inherits Exception other than the RuntimeException class, you must display the catch or throw.

(Note: The RuntimeException class is the subclass of the Exception class.)

The following code throws all exceptions.

Void func (...) throws exception {

}

Such a code is masked all anomalies including the system anomaly. In such a function, call any code that is likely to throw an exception, nor does any compiler. Moreover, the code that calls this function must be written as follows:

Try {

...

Func (..)

...

} catch (exception e) {

}

The above code can CATCH includes all anomalies within the system anomaly, generally only appear in the test program. This exception handling method shields all exceptions. It is recommended to throw a specific application exception. code show as below:

Void func (...) throws servletexception {

// If there is any other abnormality, you must pack it into a servletexception throw.

Try {

} catch (sqlexception e) {

Throw new servletexception (e);

}

}

Calling this function is written as follows:

Try {

...

Func (..)

...

} catch (servletexception e) {

}

// If you need Catch to include all anomalies within the system anomaly, you can add the following statement later.

Catch (Exception E) {}

Finally

In a function involving resource release (such as database resources, file resources), the number of functions is a problem that needs to be considered. The general solution is that try to make this function only have an exit at the end of the function. This is impossible to do this due to the complexity of logic. You can use the FINALLY mechanism to control.

For example, the following code

Void func (..) throws servletexception {

IF (...)

Return; // Won't Go Finally Block

Try {

...

IF (...)

Return; // Will Go Finally Block

...

} catch (sqlexception e) {

Throw new servletexception (e): // Will Go Finally Block

} catch (ioexception e) {

Return; // Will Go Finally Block

} finally {

// Release resource

}

}

转载请注明原文地址:https://www.9cbs.com/read-23529.html

New Post(0)