Java exception capture and processing

Source: Internet
Author: User
Tags throwable try catch

In programs that do not have exception handling, if you want to avoid exceptions, you need to use a large number of judgment statements to match the error conditions you think of to catch errors that may occur in your program. However, this will inevitably lead to inefficient operation of the program.
Java exception handling mechanism is easy to use, can customize the exception class, handle thrown exceptions, without reducing the efficiency of the program and other advantages. Therefore, in the Java programming, we should make full use of exception processing opportunities to improve the stability and efficiency of the program.
1. Exception handling examples and basic formats:

 PackageJavabasics; Public classTEST5 { Public Static voidMain (string[] args) {inti = 10; intj = 0; Try{        inttemp = i/j;//An exception is generated hereSYSTEM.OUT.PRINTLN ("Calculated result:" +temp); }Catch(Exception e) {System.out.println ("Exception occurred:" +e);//Print exception InformationE.printstacktrace ();//Print the complete exception information}finally{System.out.println ("Execute this code whether or not an exception occurs"); } System.out.println ("End of calculation"); }}


The running result of the program Wei:

Exception occurred: java.lang.ArithmeticException:/by zero
Executes this code regardless of whether an exception occurs
End of calculation

2.Exception and Error

Common:
Exception and error are the two most commonly used classes in the Java exception structure, collectively known as exceptions. They're all throwable subclasses.
Different points:
Exception represents an exception encountered in a program and can be captured with a try Catch
Error generally refers to JVM errors, which cannot be captured in the program

(Extension: Throwable is the parent of exception, can you directly use Throwable?

First, using Throwable to catch exceptions, there is no problem in the code, but in development generally do not use throwable processing, because it has exception and error two sub-class, error itself does not need program processing, and the program needs to deal with exception, so there is no need to use throeable)

3.Throw and Throws Keywords

Throws: When defining a method, use the Throws keyword declaration, which means that the method does not handle the exception, but instead gives the calling method to handle

(Note: Do not use the Throws,main method in the main method as the starting point for all methods, and all operations are initiated by the main method, so if you use throws in the Main method, then the problem is definitely referred to the JVM, which will cause the program to break.) )

The Throw:throw keyword is an artificially thrown exception that directly throws an instantiated object of the exception.

Package Javabasics;public class Test5 {public static void main (string[] args) {try{throw new Exception ("Throw an exception yourself");//Throw an exception to the real Instantiate Object}catch (Exception e) {e.printstacktrace ();//Catch Exception}}}

Application examples of throw and throws combinations:

The following code is also used in the development of more processing methods

Package Javabasics;public class Math {public int div (int i,int j) throws Exception{int temp = 0;try{temp = i/j;} catch (Exception e) {//catch exception throw e;//the exception to the handle}FINALLY{SYSTEM.OUT.PRINTLN ("End of Calculation");} return temp;}} Package Javabasics;public class Test5 {public static void main (string[] args) {Math math = new math (); try {System.out.prin TLN (Math.div (10, 0));} catch (Exception e) {//For exception capture//TODO auto-generated catch Blocke.printstacktrace ();}}}

Program execution Results:

End of calculation
Java.lang.ArithmeticException:/By zero
At JavaBasics.Math.div (math.java:7)
At JavaBasics.test5.main (Test5.java:8)

4. Custom exception classes:

Package Javabasics;public class MyException extends exception{//custom Exception class inheritance Exception class public myexception (String msg) {// The construction method accepts the exception information Super (MSG);//Call the constructor method in the parent class}}package Javabasics;public class Test5 {public static void main (string[] args) {try{ throw new MyException ("Custom exception Information");//Throws Exception}catch (Exception e) {//Exception capture processing e.printstacktrace ();}}}

  

Execution Result:

Javabasics.myexception: Custom Exception information
At JavaBasics.test5.main (test5.java:7)

5.Exception and RuntimeException

The following example:

Package Javabasics;public class Test5 {public static void main (string[] args) {String str= "123a"; int temp = Integer.parsei NT (str);//convert string to int type System.out.println (temp*temp);}} Execution result: Exception in thread "main" Java.lang.NumberFormatException:For input string: ' 123a ' at Java.lang.NumberFormatException.forInputString (numberformatexception.java:65) at Java.lang.Integer.parseInt ( integer.java:492) at Java.lang.Integer.parseInt (integer.java:527) at JavaBasics.test5.main (Test5.java:7)

Executive newspaper NumberFormatException Obviously, the program has been interrupted, look at the parseint method of the integer class source can be seen throws thrown numberformatexception to the method call processing.

public static int parseint (String s) throws NumberFormatException {
return parseint (s,10);
}

NumberFormatException is a subclass of the RuntimeException class

Can be drawn:

Exception must use Try ... in the program. Catch processing.

RuntimeException can be used without a try ... Catch processing, which causes an exception to be processed directly to the JVM. (It's best to use try ... in development.) Catch for processing)

Java exception capture and processing

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.