Handling Errors
Due to an error causing some operations to be incomplete, the program is due to:
- Returns to a security state and allows the user to execute some other command
- Allows the user to save the results of all operations and terminate the program in an appropriate manner
Issues to be concerned with:
- User input Error
- Device error
- Physical limitations
- Code Error
When a method is not able to perform its task with a normal path, it can exit the method by another path. In this case, the method does not return any values, but instead throws a (throw) object that encapsulates the error message. Note that this method exits immediately and does not return any values. The code that calls this method will not be able to proceed, and the exception handling mechanism begins to search for the exception handler (exception handler) that can handle this exception condition.
Exception classification
All derived from the Throwable class, decomposed into two branch hierarchies: Error and Exception
- The error class hierarchy describes internal errors and resource exhaustion errors for the Java runtime system. The application should not throw this error.
- The Exception class hierarchy consists of two branches.
- The exception that is derived from the runtimeexception exception, which is caused by a program error.
- Other exceptions are not program-induced.
Several cases that derive from the RuntimeException exception:
- Wrong type conversions
- Array access out of bounds,
ArrayIndexOutOfBoundsException
exception
- Access null pointer,
NullPointerException
exception
A few other exceptions:
- Attempting to read data behind the end of the file
- Attempting to open a file that does not exist
- An attempt was made to look up a class object based on a given string, and the string represented by it does not exist
Java will be born in the Error class or runtieexception all exceptions become non-checked exceptions , and other exceptions become the exception to be checked .
Declaring an exception to be checked
A method not only tells the compiler what values to return, but also tells the compiler what errors might occur .
Example:
public FileInputStream(String name) throws FileNotFoundException { ...}
This declaration indicates that an exception could be thrown, and if this exception occurs, the constructor will not initialize a new FileInputStream object, but instead throw a FileNotFoundException class object. When an exception class object is thrown, the runtime searches for the exception handler to specify how the FileNotFoundException object is handled.
Situations in which exceptions need to be thrown:
- Invokes a method that throws a checked exception.
- An error was found during the run of the program, and a throw statement was used to throw a checked exception.
- There are errors in the program, some objects that are not being checked.
- An internal error occurred with the Java virtual machine and the run-time library.
In the first two cases, it must be told that the programmer calling this method might throw an exception. Prevents the program from encountering an abnormal stop thread.
Depending on the exception specification , the method header declares that this method may throw an exception, and multiple checked exceptions are separated by commas:
class MyAnimation{ ... publicloadImagethrows IOException, FileNotFoundException { ... }}
If the method does not declare the exception being checked, the compiler issues an error message.
In addition to declaring exceptions, exceptions can be caught and thrown to allow the exception handler to process.
Additionally: declares an exception, which may throw a subclass exception for this exception.
Throw exception
The statement that throws the exception:
thrownewreadDatathrows EOFException { ... while (...) { if (!in.hasNext//EOF encountered ifthrownew EOFException(); } }}
Thrown with the exception class that exists:
- Find a suitable exception class
- Create an object of this class
- Throws an Object
Once the method throws an exception, this method cannot be returned to the caller.
Create Exception class
Standard exceptions do not adequately describe the problem, and you can create your own exception classes:
class FileFormatException extends IOException { public FileFormatException(){} public FileFormatException(String gripe){ super(gripe);//构造一个带描述信息的异常 }}//抛出自己定义的异常类型String readDate(BufferedReader in) throws FileFormatException { ... while (...) { if (ch == -1) { //EOF encounteered if (n < len) throw new FileFormatException(); } ... } return s;}
Api:
//java.lang.ThrowableThrowable() 构造一个 Throwable 对象,没有描述信息。Throwable(String message) 构造一个 Throwable 对象,带描述信息。String getMessage() 获取描述信息。
# Catching exceptions
Catching exceptions
The exception occurs, no capture, the program terminates execution, and the exception information is printed on the console.
To capture a row, you must set the Try/catch statement block:
try { code more code} catch (ExceptionType e) { handler for this type}
If there is code in the try that throws the exception defined in the catch:
- The program skips the rest of the code in the TRY statement block.
- The program executes the processor code in the catch clause.
Note: If there is an exception catch in the try, the program terminates.
To pass an exception to the caller:
public void read(String filename) throws IOException {...}
The exception that does not know how to handle continues to pass, passing the exception using the throws specifier, telling the caller that this method might be an exception.
Exception : If you write a method that overrides a superclass and the method does not throw an exception, this method must capture every checked exception that appears in the method code. The exception class range listed by the superclass method is not allowed to appear in the throws specifier of a subclass.
Capturing multiple exceptions
There are two ways to use a separate catch clause for each exception class in the first way.
try { code;} catch (FileNotFoundException e) { emergency action;} catch (UnknownHostException e) { emergency action;} catch (IOException e) { emergency action;}
The second way you can combine a catch clause with a motive-like exception.
try { code;} catch (FileNotFoundException | UnknownHostException | IOException e) { emergency action;}
To get more information about an object, you can:
e.getMessage();e.getClass().getName();
Note: When capturing multiple exceptions, the exception variable is implied as a final variable and cannot be modified.
Throw exception and exception chain again
Some exceptions we do not want to specify the reason for sending the error details, but want to explicitly specify whether it has a problem:
try { access the database} catch (SQLException e) { throw new ServletException("database error:" + e.getMessage());}//更好的方法,将原始异常设置为新异常的“原因”try { access the database} catch (SQLException e) { Throwable se = new ServletException("database error"); se.initCause(e); throw se;}//重新得到原始异常Throwable e = se.getCause();
This check exception, not allowed to throw it, packaging technology is very useful, you can catch this check exception, wrap it up as a run-time exception.
Finally clause
The code in the FINALLY clause is executed, whether or not an exception is caught:
InputStream in = new FileInputStream(...);try { core 1; core 2;} catch (IOException e) { core 3;} finally { core 4;}
There are 3 things to be experienced:
- The code is not an exception. Executes the try block and then executes the finally block.
- Throws an exception. Executes the try block until the exception is known, skips the remaining try code, goes through the code in the catch clause that matches the exception, and finally executes the code in the finally clause.
- The code throws an exception, but the catch has no matching exception. Executes the try block until the exception is known, skips the remaining try code, goes to execute the code in the finally clause, and throws the exception to the caller of the method.
decoupling try/catch
and try/finally
, improve the clarity of the code:
try { try { code; } finally { in.close(); }} catch (IOException e) { show error message;}
The inner layer ensures that the input stream is closed, and the outer layers ensure that errors are reported. The outer layer also reports errors that occur in the finally clause.
return of the various scenarios :
- When return is in a try block, the contents of the last-finally clause are executed when the method returns.
- When return is present in the TRY block finally clause, the return value in the finally clause overrides the original return value.
The disadvantages of the finally clause
try { 1finally { in.close();}
If the try statement throws some non-ioeception exceptions, these exceptions can only be handled by the caller. Executes a finally statement block and calls the Close method, possibly throwing a IOException exception. In this case, the original exception is lost and instead throws the exception of the Close method.
Try statement with Resource
When a resource belongs to a class that implements the Autocloseable interface:
//接口的一个方法void close() throws Exception//最简形式try (Resource res = ...) { work with res;}
When the try block exits, Res.close () is called automatically. And you can specify multiple resources.
Parsing stack trace elements
A stack trace element is a list of method invocation procedures that contain specific locations for method calls during program execution.
Call the Printstacktrace method of the Throwable class to access the text description information for the stack track.
Tips for using exception mechanisms
- Exception handling is not a substitute for simple testing
- Do not refine the exception excessively
- Using exception hierarchies
- Do not suppress exceptions
- "Harsh" is better than laissez-faire when detecting errors
- Don't be ashamed to pass the exception
Using the concept of assertion assertions
The assertion mechanism allows some check statements to be inserted into the code during testing. These inserted detection statements are automatically removed when the code is published.
assert 条件;和assert 条件 : 表达式;
Both of these forms detect the condition and throw a Assertionerror exception if the result is false. In the second form, the expression will be assertionerror to the constructor of the descendant and converted to a message string. The purpose of the expression section is to produce a message string.
example, assert that X is a non-negative value:
assert x >= 0;assert x >= 0 : x;
Enabling and disabling assertions
Enable:java -enableassertions MyApp
To enable assertions in a class:java -ea:MyClass -ea:com.mycompany.mylib... MyApp
To disable assertions for specific classes and packages:java -ea:... -da:MyClass MyApp
You cannot apply a system class that does not have a classloader, to use:-enablesystemassertions/-esa
Using assertions to complete parameter checking
Use the assertion scenario:
- Assertion failure is a fatal, unrecoverable error
- Assertions for development and test phases
Non-notification of recoverability errors should not be used as a means of informing users of problems.
This method is not allowed to be called with a null array, and an assertion is used at the beginning of this method:assert a != null;
Assume the use of assertions for documentation
if (i % 3 == 0) ...else if (i % 3 == 1) ...else //i % 3 ==2 assert i >= 0;if (i % 3 == 0) ...else if (i % 3 == 1) ...else assert i % 3 ==2;
Logging Basic Log
Use the global logger and call the info method:
Logger.getGlobal().info("File->Open menu item selected");
Content:
May 10, 2013 10:23:43 PM LoggingImageViewer fileOpen
INFO: File->Open menu item selected
The following will cancel all logs at the appropriate place (e.g. main):
Logger.getGlobal().setLevel(Level.OFF);
Debugging Tips
- Print the value of any variable:
System.out.println("x=" + x);
- Place a separate main method in each class and do the unit test.
- You can use the JUnit Unit test framework.
Java Core Technology Volume 15. Java exceptions, assertions, and logs