Java Exception Handling-java Exception handling __java

Source: Internet
Author: User
Tags exception handling finally block flush stack trace throwable try catch
Java Exception Handling-java exception handling
Exceptions in JavaExceptions are programs at compile timeOr Run TimeUnexpected scenarios such as failure to comply with Java syntax rules when writing Java code can result in compilation failures, operation arrays, subscript run-time exceptions, and so on. causes an exception to exit when an exception occurs, in order to avoid the exception of the program exit, we have to the occurrence of some exception handling, let the program continue to execute, commonly known as " Exception Recovery”。
the appearance of exceptions in JavaThe occurrence of an exception generally has the following conditions: Throw Custom Exceptions The code executes the thrown exception in the exception scene, such as array of bounds anomaly, IOException, ArithmeticException, SocketException, and so on. exceptions that the JVM itself throws at run time, such as a memory overflow exception, and so on. This type of exception is called an asynchronous exception, and our program cannot handle it.

Java exception Handling

When an exception occurs when the program is running, we call it exception handling when we catch the exception and try to get the program to continue running. Exception handling changes the execution process of the program, that is, when the program is abnormal, that is, a plan fails, we execute the standby B plan, so that the business continues. which exceptions we can handle some of the run-time anomalies, even if we do, we can not allow the program to recover, such as the previous asynchronous exception, memory overflow error, and so on. Error class exception is not allowed to continue execution, exception class we can capture, handle the exception, so that the program continues to execute. Instead of capturing The error exception, we typically catch the exception exception .
exception Handling keyword Try block catch block finally block throw keyword throws keyword try-with-resources


Java exception inheritance relationship


The more important and most basic exception classes in Java are throwable,error,exception and runtimeexception.
The Throwable class is the parent of all exception classes, which cannot be thrown directly by us, and is examined by the compiler--The client exception (compiler Checked).

The error class is a subclass of Throwable that represents all the exceptions that are not recoverable. When error anomalies occur, the program exits unexpectedly even if we handle them abnormally . The error class and its subclasses are also called asynchronous exceptions . The error class is not checked by the compiler- non-client exception .

The exception class is a throwable subclass of theexception class and its subclasses are recoverable exceptions . Exception is checked by the compiler-the exception is inspected .

The RuntimeException class is a subclass of exception, and its subclasses are not checked by the compiler-- non-inspected exceptions . In general, RuntimeException can be avoided in the program, such as NullPointerException, ArithmeticException, arrayindexoutofboundexception, etc. We can use code to judge the anomalies before they occur, thus avoiding the occurrence of anomalies.


the life cycle of an exception if the program is not processed, the exception is thrown from the current stack to the top of the stack, looking for an exception handler that, if not found, will eventually be processed by the JVM stop program, and Stack trace Will default to System.err output.
If you want to save the exception stack information, we can set the default exception handling handler:

Thread.setdefaultuncaughtexceptionhandler ((thread, ex)-> {record the
exception
})
When we catch an exception, we generally do not ignore the exception that the catch block is empty, at least you must print out the exception stack information:
try {
class<?> cl = Class.forName (className);
..
} catch (ClassNotFoundException ex) {
ex.printstacktrace ();
}

If you want to save stack information, you can convert the exception stack information to a string:
Bytearrayoutputstream out = new Bytearrayoutputstream ();
Ex.printstacktrace (out);
String description = out.tostring ();

If you want to analyze the stack carefully, we can use:
Stacktraceelement[] frames = Ex.getstacktrace ();

Get stacktraceelement instance to concrete analysis, specific API reference Javadoc.


Package com.doctor.commons;
Import java.io.IOException;
Import Java.io.PrintWriter;

Import Java.io.StringWriter;

Import Com.doctor.beaver.annotation.ThreadSafe;  /** * @author sdcuike * <p> * Created on September 27, 2016 <br/>/@ThreadSafe public final class exceptionutils {public static String printstacktracetostring (final Throwable t) throws IOException {try (S
                tringwriter SW = new StringWriter (); PrintWriter pw = new PrintWriter (SW);)
            {t.printstacktrace (PW);
            Pw.flush ();
            Sw.flush ();
        return sw.tostring (); } public static String printfullstacktracetostring (final Throwable t) throws IOException {try (stringw
                riter SW = new StringWriter (); PrintWriter pw = new PrintWriter (SW);)
            {Throwable caset = t;
                while (Caset!= null) {caset.printstacktrace (PW);
         Caset = Caset.getcause ();   } pw.flush ();
            Sw.flush ();
        return sw.tostring ();
 }
    }

}






Checked and Unchecked exception-inspected and non-inspected anomaliesThese concepts are provided in the preceding article, inspected ExceptionIs the exception that is checked by Java compilation, the compiler will complain if the exception is not processed. The Throwable and exception classes and their subclasses are all inspected for exceptions. The exception must comply with catch or Declare rule, either process, or continue throwing this exception to the upper call stack.
An exception must be a try catch or throws keyword processing. Non-inspected exceptions are exceptions that are not checked by the Java compiler and are called Run-time exceptions. Subclasses inherited from RuntimeException and error are non checked exceptions.

Abnormal in anomaly system and non-inspected anomaly: The dark color represents the exception, and the light color represents the non-inspected exception.
Figure Source: Absolute java™6th Edition
----Walter Savitch©pearson Education Limited 2016 method overloading exception handling rules

When the parent class method does not throws any exceptions, the subclass cannot throws the exception being inspected, but it can throws a non-client exception.

When a parent class method throws an exception, the subclass does not have to throws any exceptions, or the throws exception must be of the same type or subclass (that is, Delete or replace exception rules ).

The error and RuntimeException classes and their subclasses should not appear in the throws list.



Reference: http://www.tutorialspoint.com/java/java_exceptions.htm

Http://tutorials.jenkov.com/java-exception-handling/index.html

Http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html

Http://www.javaworld.com/article/2076700/core-java/exceptions-in-java.html

Java 8 Exception Handling develop reliable Java applications (Black Book Series)-Mahavir DS Rathore

(https://yunpan.cn/ckzJdHGh8I78b access password e580)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.