Java exception (1) Introduction to Java exceptions and its architecture

Source: Internet
Author: User

Java exception description Java exception is a consistency mechanism provided by Java to identify and respond to errors. The Java exception mechanism separates the exception handling code in the program from the normal business code, ensures the program code is more elegant, and improves the program robustness. When an exception is used effectively, the exception can clearly answer the three questions: what, where, and why: the exception type answers the question "what" is thrown, the exception stack trace answers "where" to throw, and the exception message replies "why" to throw. Several keywords used by the Java exception mechanism: try, catch, finally, throw, and throws. • Try -- used for listening. The code to be monitored (the code that may throw an exception) is placed in the try statement block. When an exception occurs in the try statement block, the exception is thrown. • Catch -- used to catch exceptions. Catch is used to catch exceptions in the try statement block. • Finally -- the finally statement block is always executed. It is mainly used to reclaim material resources opened in try blocks (such as database connections, network connections, and disk files ). Only after the finally block is executed is the return or throw statement in the try or catch block is returned. If the finally statement uses the return or throw termination method, then it will not jump back to the execution and stop directly. • Throw -- used to throw an exception. • Throws -- Used in the method signature to declare the exceptions that the method may throw. The following are examples to briefly understand these keywords. Example 1: understand the basic usage of try and catch. Copy the code public class Demo1 {public static void main (String [] args) {try {int I = 10/0; System. out. println ("I =" + I);} catch (ArithmeticException e) {System. out. println ("Caught Exception"); System. out. println ("e. getMessage (): "+ e. getMessage (); System. out. println ("e. toString (): "+ e. toString (); System. out. println ("e. printStackTrace (): "); e. printStackTrace () ;}} copy the code execution result: Ca Ught was tione. getMessage ():/by zeroe. toString (): java. lang. arithmeticException:/by zeroe. printStackTrace (): java. lang. arithmeticException:/by zero at Demo1.main (Demo1.java: 6) Result Description: there is an operation with a division of 0 in the try statement block. This operation throws java. lang. arithmeticException exception. Catch is used to capture the exception. The observed results show that System. out. println ("I =" + I) is not executed ). This indicates that the remaining content in the try statement block will not be executed again after an exception occurs in the try statement block. Example 2: to understand the basic usage of finally, add the finally statement on the basis of "Example 1. Copy the public class Demo2 {public static void main (String [] args) {try {int I = 10/0; System. out. println ("I =" + I);} catch (ArithmeticException e) {System. out. println ("Caught Exception"); System. out. println ("e. getMessage (): "+ e. getMessage (); System. out. println ("e. toString (): "+ e. toString (); System. out. println ("e. printStackTrace (): "); e. printStackTrace ();} finally {System. out. println ("run f Inally ") ;}} copy the code running result: copy the code Caught finished tione. getMessage ():/by zeroe. toString (): java. lang. arithmeticException:/by zeroe. printStackTrace (): java. lang. arithmeticException:/by zero at Demo2.main (Demo2.java: 6) run finally copy code result Description: finally statement block is finally executed. Example 3: understand the basic usage of throws and throws. throws is used to declare thrown exceptions, while throw is used to throw exceptions. Copy the code class MyException extends Exception {public MyException () {} public MyException (String msg) {super (msg );}} public class Demo3 {public static void main (String [] args) {try {test ();} catch (MyException e) {System. out. println ("Catch My Exception"); e. printStackTrace () ;}} public static void test () throws MyException {try {int I = 10/0; System. out. println ("I =" + I);} catch (ArithmeticExce Ption e) {throw new MyException ("This is MyException") ;}} copy the code running result: Catch My ExceptionMyException: This is MyException at Demo3.test (Demo3.java: 24) at Demo3.main (Demo3.java: 13) results show that MyException is a subclass of Exception. The try statement block of test () generates an ArithmeticException (the Division is 0), and this exception is caught in catch; then the MyException exception is thrown. The main () method captures and processes the MyException thrown in test. Java exception framework Java exception architecture 1. Throwable is a class of all errors or exceptions in the Java language. Throwable contains two subclasses: Error and Exception. They are usually used to indicate exceptions. Throwable contains a snapshot of the thread execution stack when the thread is created. It provides printStackTrace () and other interfaces for obtaining stack trace data and other information. 2. Exception and its subclass are a form of Throwable, which specifies the conditions that a reasonable application wants to capture. 3. RuntimeException is a super class that may throw exceptions during the normal operation of the Java Virtual Machine. The compiler does not check for RuntimeException exceptions. For example, if the divisor is zero, an ArithmeticException is thrown. RuntimeException is a superclass of ArithmeticException. When the code divisor is zero, if either "ArithmeticException is not thrown through throws Declaration" or "try... catch... to handle this exception, you can also compile it. This is what we call "the compiler will not check for RuntimeException exceptions "! If the code generates a RuntimeException, you must modify the code to avoid it. For example, if the divisor is zero, you need to use the code to avoid this situation! 4. Like Exception, Error is also a subclass of Throwable. It is used to indicate serious issues that a reasonable application should not try to capture, and most such errors are exception conditions. Like RuntimeException, the compiler does not check for errors. Java divides the Throwable structure into three types: Checked Exception, RuntimeException, and Error ). (01) runtime exception definition: RuntimeException and its subclass are called runtime exceptions. Feature: the Java compiler does not check it. That is to say, when such exceptions may occur in the program, if "throws declaration is not used to throw it" or "try-catch statement is not used to catch it", compilation will still pass. For example, the ArithmeticException generated when the divisor is zero, the IndexOutOfBoundsException exception generated when the array is out of bounds, and the ConcurrentModificationException exception generated by the fail-fail mechanism are all runtime exceptions. Although the Java compiler does not check for runtime exceptions, we can also throw it through throws declaration, or capture it through try-catch. If an exception occurs during running, you must modify the code to avoid it. For example, if the divisor is zero, you need to use the code to avoid this situation! (02) definition of the Exception to be checked: The Exception class itself, and other subclasses except for the "RunTime Exception" in the Exception subclass belong to the checked Exception. Feature: the Java compiler checks it. This type of exception can either be declared and thrown through throws or captured through try-catch. Otherwise, the exception cannot be compiled. For example, CloneNotSupportedException is a checked exception. When an object is cloned through the clone () interface, and the corresponding class of the object does not implement the Cloneable interface, a CloneNotSupportedException exception is thrown. Exceptions are usually recoverable. (03) Error definition: Error class and its subclass. Features: the compiler does not check errors like running exceptions. An error occurs when resources are insufficient, constraints fail, or other programs cannot continue to run. The program itself cannot fix these errors. For example, VirtualMachineError is an error. According to Java conventions, we should not implement any new Error subclass! Which of the above three structures should we use when throwing exceptions or errors? The suggestion in objective Java is: an exception is checked for recoverable conditions and an exception occurs when a program error occurs during running.

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.