Java Exception Handling

Source: Internet
Author: User
Tags stub

1. Exception Handling

1) Exception handling mechanism

When an exception is thrown in the program, the program jumps out of the code that caused the exception in the program, the Java Virtual machine detects the catch block that handles the exception that matches the Try keyword, if found, gives control to the code in the Catch block, and then proceeds to execute the program. The code for the exception that occurred in the try block is not re-executed. If no catch block is found to handle the exception, the current thread that encounters the exception is terminated after all finnally block code is executed and the Uncaughtexception method of the Threadgroup to which the current thread belongs is called.

2) exception capture and handling

2.1) Throwable, Error, Exception

There are throwable classes defined in the Java exception structure, and error and exception are two of their derived subclasses. Where exception represents an exception due to network failure, file corruption, device errors, illegal user input, and so on, this type of exception can be handled through the Java exception capture mechanism. Error indicates errors in the Java Runtime environment, such as JVM memory overflow.

2.2) Try-catch

The Try statement specifies a piece of code that is the scope for capturing and handling exceptions at once. During execution, the code may produce and throw one or more types of exception objects, which are followed by a catch statement that handles each of these exceptions accordingly.

If no exception is generated, all the catch code snippets are skipped and not executed.

In a catch statement block is the code that processes the exception, and the exception declared in the catch is the information that encapsulates the exception event, and some of the methods of the object can be used in the CATCH statement block to obtain the information.

public class Try_catchdemo {public static void main (string[] args) {System.out.println ("program started"); try{string str = null; System.out.println (str);} catch (NullPointerException e) {System.out.println ("Null pointer exception appears"); SYSTEM.OUT.PRINTLN ("program ended");}} /* Run Result: Program started NULL program ended */

2.3) Multiple Catch

Each try statement can accompany one or more catch statements to handle the different types of exceptions that may occur. Catch-caught exception types from top to bottom catch exception types in the order that they should be subclasses to the parent class.

Usually when writing code, the exception should be captured in the last cathc, which guarantees that the failure of the catch will cause the program to terminate because of an exception that is not declared in the catch.

public class Try_catchdemo {public static void main (string[] args) {System.out.println ("program started"); try{string str = "a"; System.out.println (str); System.out.println (Str.charat (0)); SYSTEM.OUT.PRINTLN (Integer.parseint (str)); System.out.println ("I am a pseudo-code");} catch (NullPointerException e) {System.out.println ("Null pointer exception appears"); catch (Stringindexoutofboundsexception e) {System.out.println ("string subscript out of Bounds");} catch (Exception e) {System.out.println ("exception occurred");} SYSTEM.OUT.PRINTLN ("program ended");}}

Try block, if an exception occurs, then the code from the beginning of this exception code will not be executed, such as the previous case of the word Poute exception, the following two lines of code will not be executed.

2.4) finally

The finally statement provides a unified exit for exception handling, enabling unified management of the program's state before the control process is transferred to other parts of the program.

The code specified by the finally is executed regardless of whether the block specified in the try is thrown or not, usually in the finaly statement, such as closing open files, deleting temporary files, and so on.

A finally statement block can only be defined once after a try statement block, or after the last catch statement block.

public class Try_catchdemo {public static void main (string[] args) {System.out.println ("program started"); try{string str = null; System.out.println (str); System.out.println (Str.charat (0)); SYSTEM.OUT.PRINTLN (Integer.parseint (str)); System.out.println ("I am a pseudo-code");} catch (NullPointerException e) {System.out.println ("Null pointer exception appears"); catch (Stringindexoutofboundsexception e) {System.out.println ("string subscript out of Bounds");} catch (Exception e) {System.out.println ("exception occurred");} Finally{system.out.println ("I am the real code, must be executed");   The code in the finally statement block executes}SYSTEM.OUT.PRINTLN regardless of whether an exception occurred ("The program ended");}} /* Run Result: null pointer exception at start of the program I am the real code, must execute the program ended/

2.5) Throw keyword

When a program fails to process, it throws the corresponding exception object, and at some point you may want to throw the exception yourself. For example, after the end of exception processing, and then throw the exception, let the next layer of exception handling block to catch, if you want to throw an exception, you need the throw keyword, and generate the specified exception object.

public class Exception_throw {public static void main (string[] args)  {person p = new person (); try {p.setage (+);} CA TCH (Exception e) {e.printstacktrace ();} System.out.println ("Age:" +p.getage ());}} class person{private int age;public int getage () {return age;} public void Setage (int.) throws Exception{if (age<0| | age>100) {throw new Exception ("Invalid Age");} This.age = Age;}} /* Run Result: java.lang.Exception: Age not valid at Javase.day08.Person.setAge (exception_throw.java:22) at Javase.day08.Exception_ Throw.main (exception_throw.java:7) Age: 0 * *

2.6) throws keyword

Many methods are declared in the program, which may throw exceptions due to some errors, but you do not want to handle these exceptions directly in this method, and you want to call this method to unify the processing, you can use the throws keyword to declare this method will throw an exception.

public class Exception_throw {public static void main (string[] args) is throws Exception {person p = new person ();p. Setage (10 00); System.out.println ("Age:" +p.getage ());}} class person{private int age;public int getage () {return age;} public void Setage (int.) throws Exception{if (age<0| | age>100) {throw new Exception ("Invalid Age");} This.age = Age;}} /* Run Result: Exception in thread "main" java.lang.Exception: Age not valid at Javase.day08.Person.setAge (exception_throw.java:18) at Javase.day08.Exception_throw.main (EXCEPTION_THROW.JAVA:6): */

Note: It is common to use throws on the current method to notify the caller to handle the exception when an exception is thrown in a method, and only throws the RuntimeException compiler does not require this to be done, except that Declaring the class exception compiler without using throws does not pass.

public class Exception_throw {public static void main (string[] args) {person p = new person ();p. Setage (1000); System.out.println ("Age:" +p.getage ());}} class person{private int age;public int getage () {return age;} public void Setage (int.) {if (age<0| | age>100) {throw new RuntimeException ("Invalid Age");} This.age = Age;}} /* Run Result: Exception in thread "main" java.lang.RuntimeException: Age is not legal at Javase.day08.Person.setAge (exception_ THROW.JAVA:18) at Javase.day08.Exception_throw.main (exception_throw.java:6) */

  

2.7) throws when overriding a method

When using inheritance, a method on a parent class declares that throws throws some exceptions, and when overridden in a subclass, we can do the following:

    • Exception not handled (throws not declared when overriding method)
    • Partial exceptions declared in the parent class can be declared in throws only
    • Subclass exceptions for exceptions thrown in parent class methods can be declared in throws

However, you cannot do the following:

    • Declaring an extra exception in throws when overriding a method
    • The parent class exception that is declared in the parent class method is declared in throws when overriding a method
Import Java.awt.awtexception;import Java.io.filenotfoundexception;import Java.io.ioexception;import Java.sql.sqlexception;public class Exception_throws {public void Dosome () throws Ioexception,awtexception{}}class Son Extends exception_throws{//can no longer throw any exceptions//public void Dosome () {////}////can only throw a partial exception//public void Dosome () throws ioexception{////}//can throw a parent class method that throws an exception to the subtype exception//public void Dosome () throws filenotfoundexception{////}//does not allow an extra exception to be thrown//public void Dosome () throws sqlexception{////}//does not allow throwing a parent class method throws an exception to the parent type exception//public void Dosome () throws exception{////}}

  

2.Java Exception API

1) runtimeexception

Java exceptions are classified as detectable exceptions, non-detection exceptions.

Detectable exceptions: Detectable exceptions are validated by the compiler, and for any method that declares an exception, the compiler enforces a processing or declaration rule, does not catch the exception, and the compiler does not allow compilation.

Non-detection exceptions: Non-detection exceptions do not follow processing or claim rules. When such an exception is generated, it is not necessary to take any appropriate action, and the compiler does not check whether the exception has been resolved.

The RuntimeException class is a non-detection exception, because runtime exceptions caused by ordinary JVM operations can occur at any time, and such exceptions are typically raised by specific operations. However, these operations occur frequently in Java applications. Therefore, they are not restricted by the compiler's checking and processing or declaring rules.

2) Common RuntimeException

IllegalArgumentException: Throws an exception indicating that an invalid or incorrect parameter was passed to the method

NullPointerException: Thrown when an application tries to use null where the object is needed

ArrayIndexOutOfBoundsException: This exception is thrown when an array subscript is used that exceeds the allowable range of the array

ClassCastException: Throws this exception when attempting to cast an object to a subclass other than the instance

NumberFormatException: Thrown when an application attempts to convert a string to a numeric type, but the string cannot be converted to the appropriate format

3.Exception Common API

1) printstacktrace

Throwable defines a method that can output error messages to track the contents of the stack when an exception event occurs.

Method definition: void Printstacktrace ()
try{...  } catch (Exception e) {    e.printstacktrace ();  Output execution Stack information}

2) GetMessage

A method is defined in Throwable to get information about an exception event.

Method definition: String getMessage ()
try{...  } catch (Exception e) {    System.out.println (e.getmessage ());}

3) Getcause

Many times, when an exception is thrown by another exception, the Java library and open source will wrap an exception in another exception. At this point, logging and printing root exceptions become very important. The Java exception class provides the Getcause () method to retrieve the cause of the exception, which can provide more information about the cause of the root level of the exception. This Java practice is a great help in debugging or troubleshooting your code. In addition, if you want to wrap an exception into another exception, a new exception will be constructed to pass the source exception.

Throwable Getcause ()

Case: Printstacktrace getmessage Demo

public class Exception_throw {public static void main (string[] args) {person p = new person (); try {p.setage (+);} catch (Exception e) {E.printstacktrace (); System.out.println (E.getmessage ());} System.out.println ("Age:" +p.getage ());}} class person{private int age;public int getage () {return age;} public void Setage (int.) throws Exception{if (age<0| | age>100) {throw new Exception ("Invalid Age");} This.age = Age;}} /* Run Result: java.lang.Exception: Age not valid at Javase.day08.Person.setAge (exception_throw.java:23) at Javase.day08.Exception_ Throw.main (Exception_throw.java:7) Age not legal age: 0 */

  

4. Custom exception

1) Meaning of custom exceptions

Java exception mechanisms ensure that programs are more secure and robust. Although the Java class Library already offers many classes that can handle exceptions directly, it is sometimes necessary for developers to customize exceptions to capture and handle exceptions more accurately for a better user experience.

2) inherit exception custom exception

To create a custom exception class syntax:

public class custom Exception class name extends exception{...     }

3) Writing Construction methods

When a custom exception is defined, the appropriate construction method can be generated from eclipse.

    1. Declare a class and inherit exception
    2. Right click on source
    3. select Generate constructors from Superclass
    4. Confirm Build
    when all construction methods in the parent class are selected
public class MyException extends Exception{public myexception () {super ();//TODO auto-generated constructor stub}public myexception (String Message, Throwable Cause, Boolean enablesuppression, Boolean writablestacktrace) {super (message, cause, Enablesuppression, writablestacktrace);//TODO auto-generated constructor stub}public myexception (String message, Throwable cause) {Super ( message, cause);//TODO auto-generated constructor stub}public myexception (String message) {super (message);//TODO auto-generated constructor stub}public MyException (Throwable cause) {super (cause);//TODO auto-generated constructor stub}}

  

  

Java Exception Handling

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.