Exceptions, assertions and logging

First, abnormal

Abnormal objects are derived from Throwable an instance of the class that all exceptions are Throwable inherited by the next layer into the Error and Exception

Error is wrong can not handle, describing internal error java runtime errors and system resources depleted, regardless of the code writers, these errors are not checked because they are outside of the control and processing power of the application

Exception is divided into two branches, a branch derived from a RuntimeException, further comprising another branch exception rule is divided, by the program belongs to a RuntimeException exception errors; procedure itself is no problem, but the term I / O errors such problems caused by abnormal belong to other abnormalities.

A RuntimeException comprising the following operations:

Error type conversion, array access out of bounds, null pointer access

IOException exceptions include:

Attempt to read the data in the back end of the file, an attempt to open the file does not exist, a Class object trying to find the given string, and the string representation of the class does not exist.

Java exceptions (including Exception and Error) to be investigated into abnormal and abnormality can not check.

Can be checked exception (the compiler requires an exception must be disposed of):

In addition to its subclasses RuntimeException other Exception class and its subclasses are checked exception belong to. This unusual feature is the Java compiler will check it, that is to say, such an exception may occur when the program or capture it with the try-catch statement, either with a throws clause declared throws it, otherwise the compiler will not pass .

Not checked exception (the compiler does not require unusual compulsory disposal):

Include abnormal (a RuntimeException its subclasses) and error (Error) is running.

Exception This anomaly points abnormal and non-runtime exceptions (compiled abnormal) two categories runtime. Program should be to deal with these exceptions as possible.

Operation at (RuntimeException):

As a NullPointerException (null pointer exception), an IndexOutOfBoundsException (subscript bounds exception), these abnormalities are not checked exception, capturing processing program may be selected, or may not handle. These abnormalities are generally caused by the program logic errors, the program should avoid such abnormal logically possible.

Runtime exception is characterized by a Java compiler does not check it, that is to say, such an exception may occur when the program even without a try-catch statement catches it, throws clause declared useless throw it, will compile.

 Abnormality (abnormality compilation) Non-operating: a fall on the Exception class and its subclasses other than a RuntimeException type. From a linguistic point of view the program is an exception must be handled, if not addressed, the program will not compile. As IOException, SQLException Exception and other user-defined exception, no custom abnormalities in general.

 

1, exception handling mechanism

Throw an exception:

When a method throws an exception error occurs, the exception object methods to create and deliver the system is running, the exception object contains the exception type and program status at the time of abnormal abnormal information. The runtime system is responsible for finding and disposal of abnormal code execution

Catch exceptions:

The system starts to run from the abnormal method, the method call stack in order to check back until the method containing the appropriate exception handler to find and execute. When operating the system walks the call stack without finding an appropriate exception handler, the runtime system is terminated. At the same time, the termination means that Java programs.

 

For runtime exceptions, errors, they are not checked exception, the exception will be run by these java system automatically thrown, allowing the method without any throw, run the application ignores the runtime exception.

You can check for abnormalities (abnormal non-operating), or throw, or capture, or compile-time error.

Any JAVA code can be thrown by the throw statement,

NOTE:

Thrown from the method throws an exception clause must be used.

Use try-catch or try-catch-finaly statement to catch the exception

In short, can check for abnormalities must be captured, or throw statement, often not allowed to ignore RuntimeException and Error.

 

2, catch exceptions (try, catch, finally)

2.1 try-catch statement

try {

    // 可能会发生异常的程序代码

} catch (Type1 id1){

    // 捕获并处置try抛出的异常类型Type1

}

catch (Type2 id2){

     //捕获并处置try抛出的异常类型Type2

}

 

A pair of rear braces keyword will try an abnormal code may wrap area called monitoring. Java method exception occurs during operation, the exception object is created. The exception is thrown outside the surveillance zone by the Java runtime system attempts to find a matching catch clause to catch the exception. If a matching catch clause, then run its exception handling code, the end of the try-catch statement, other catch clauses no longer have the opportunity to match and capture the exception.

For a plurality of exception programs catch clause, we should try to capture the catch clause exception class bottom on the front, and try to capture the opposing catch top on the back clause exception classes. Otherwise, capture the underlying exception class catch clause will likely be shielded.

 

 In the matching process: If the exception object is thrown exception class belonging catch clause, or belonging to subclass of this class exception, the exception that the type of the exception object generated catch block catches match.

try { // try监控区域


if (b == 0) throw new ArithmeticException(); // 通过throw语句抛出异常

System.out.println("a/b的值是:" + a / b);

}

catch (ArithmeticException e) { // catch捕捉异常

System.out.println("程序出现异常,变量b不能为0。");

}

ArithmeticException是RuntimException的子类,而运行时异常将由运行时系统自动抛出,不需要使用throw语句

 

 

2.2 try-catch-finally statement

 

  try {

// 可能会发生异常的程序代码

} catch (Type1 id1) {

// 捕获并处理try抛出的异常类型Type1

} catch (Type2 id2) {

// 捕获并处理try抛出的异常类型Type2

} finally {

// 无论是否发生异常,都将执行的语句块

}

Regardless of whether the catch statement catches an exception, the finally clause will be executed

 

to sum up:

T R & lt Y blocks: a catch exceptions. Thereafter be zero or more catch blocks, if there is no catch block, must be followed by a finally block.

catch block: a process to try to capture the exception.

finally block: whether to capture or handle exceptions, finally block will be executed in a statement

Note: When the return try block and the catch block, finally statement block will be executed before the method returns

Case finally statement is not executed:

①finally statement ② exception occurs in the preceding code with the System.exit () to exit the program where the program ③ ④ closed the thread death CPU

Execution order try, catch, finally statement block

1) When not try to capture exception: try statement statement blocks are executed one by one, the program will skip the catch block, and finally block execute subsequent statements;

2) When the abnormality try to capture, there is no catch block this abnormality processing: When abnormality in the try block of a statement appears without processing this exception catch block, this exception will be thrown to the JVM treatment, the statement in the finally block will still be executed, but the statement after the finally block will not be executed;

3) When try to capture the exception, the catch block to handle this situation there exception: in the try block is performed in the order, when a statement is executed to a certain abnormality occurs, the program will jump to the catch block, and the match is the catch block, to find the corresponding processing program, the other catch block will not be executed, the try block, an abnormality occurs after the statement is not executed, executed after the catch block, finally block execute in the statement, and finally execute the statement after the finally block;

 

3, throw an exception (any code can throw an exception)

If a method might throw an exception, but can not afford to throw an exception, you can use throws clause specifies exceptions thrown in the method declaration

Allowed to throw multiple exceptions, when a method throws an exception, these methods will not make a deal types and subtypes, but threw the method calls the method, to deal with it, if you have been thrown up can not be resolved, there JVM for processing.

methodname throws Exception1,Exception2,..,ExceptionN

{

}

 

Throw the exception rule

 1) If it is not checked exception (unchecked exception), ie Error, RuntimeException or a subclass, you can not use the throws keyword to declare an exception to be thrown, the compiler can still pass, but in the run-time system will be thrown.

 2) must declare the method can throw any checked exception (checked exception). That is, if a method may appear to be investigated by an exception, either captured by try-catch statement, either with a throws clause declared throw it, otherwise it will cause a compiler error

3) only if an exception is thrown, the caller of the method or process it must re-throw the exception. When the caller of the method of inability to handle the exception, it should continue to throw, rather than gulping.

 4) call processing method must follow any rules and declarations can be found exception. If override a method, you can not declare an exception and cover different methods. Any kind or a subclass must be declared to be abnormal overridden method declaration.

 

4, custom exception

package Test;

import java.lang.Exception;

public class TestException {

static int quotient(int x, int y) throws MyException { // 定义方法抛出异常

if (y < 0) { // 判断参数是否小于0

throw new MyException("除数不能是负数"); // 异常信息

}

return x/y; // 返回值

}

public static void main(String args[]) { // 主方法

int  a =3;

int  b =0;

try { // try语句包含可能发生异常的语句

int result = quotient(a, b); // 调用方法quotient()

} catch (MyException e) { // 处理自定义异常

System.out.println(e.getMessage()); // 输出异常信息

} catch (ArithmeticException e) { // 处理ArithmeticException异常

System.out.println("除数不能为0"); // 输出提示信息

} catch (Exception e) { // 处理其他异常

System.out.println("程序发生了其他的异常"); // 输出提示信息

}

}


}

class MyException extends Exception { // 创建自定义异常类

String message; // 定义String类型变量

public MyException(String ErrorMessagr) { // 父类方法

message = ErrorMessagr;

}


public String getMessage() { // 覆盖getMessage()方法

return message;

}

}


Throwable常用的方法

 getCause():返回抛出异常的原因。如果 cause 不存在或未知,则返回 null。

getMeage():返回异常的消息信息。

printStackTrace():对象的堆栈跟踪输出至错误输出流,作为字段 System.err 的值

 

Second, the assertion

Assertion may be considered abnormal advanced form of assertion mechanism allows the code to insert some checking statements during the test, when the code release, these statements will be inserted automatically detects removal (if thrown or catch exceptions, the code will It has been retained in the program).

 Assertions can come in two forms

 1.assert Expression1

 2.assert Expression1:Expression2

 Expression1 which should always be a Boolean value, Expression2 string failure message is output when the assertion failure.

If Expression1 is false, throw a AssertionError, (this is a mistake, rather than an exception), that is not a checked exception, AssertionError because it is wrong, it can not capture, but this is not recommended, because that will make your system into an unstable state.

 

Assertion is off by default, to enable assertions at compile time, enable and disable assertions and -da parameters can be used -ea

 

 

 

 

 

 

 

Published 71 original articles · won praise 42 · views 60000 +

Guess you like

Origin blog.csdn.net/dreame_life/article/details/102690901