Exception Handling in Java

Source: Internet
Author: User
Tags define local finally block throw exception

Basic concepts of exceptions

Exception: An exception is a flow of instruction that causes the program to run, and if the exception is not properly handled, it may lead to the execution of the program, resulting in unnecessary loss, so in the design of the program must consider the occurrence of various anomalies, and properly do the appropriate processing, so as to ensure the normal operation of the program.

For the purpose of exception handling?


public class Exceptiondemo01{public static void Main (String args[]) {System.out.println ("********** calculation begins ***********"); int i = 10;//define integer variable int j = 0;//define integer variable int temp = i/j;//This produces an exception System.out.println ("The result of dividing two numbers:" + temp); SYSTEM.OUT.PRINTLN ("********** calculation ends ***********");};

Once an exception is generated, the statement after the exception does not execute, but instead ends the program directly and reports the error to the user.

In the history of the computer there are two major killers: power outage, the divisor is 0

Handling Exceptionsif you want to handle exceptions, you must master the processing format of the exception.
to capture an exception:
public class Exceptiondemo02{public static void Main (String args[]) {System.out.println ("********** calculation begins ***********"); int i = 10;//define integer variable int j = 0;//define integer variable Try{int temp = i/j;//This generates an exception System.out.println ("The result of dividing two numbers:" + temp); System.out.println ("----------------------------");} catch (ArithmeticException e) {System.out.println ("An exception occurred:" + e);} SYSTEM.OUT.PRINTLN ("********** calculation ends ***********");};



Process of execution of the program


The above operation code only uses the basic exception handling format: Try...catch, catch exception in try, the code after the exception will no longer be executed, but jump to the corresponding catch to execute, to handle the exception.

Of course, for exceptions can also set a unified export, using finally to complete.

public class Exceptiondemo03{public static void Main (String args[]) {System.out.println ("********** calculation begins ***********"); int i = 10;//define integer variable int j = 0;//define integer variable Try{int temp = i/j;//This generates an exception System.out.println ("The result of dividing two numbers:" + temp); System.out.println ("----------------------------");} catch (ArithmeticException e) {//Catch arithmetic exception System.out.println ("An exception occurred:" + e);} finally{//as an exception for the unified export SYSTEM.OUT.PRINTLN ("Execute this code regardless of whether an exception occurs);} SYSTEM.OUT.PRINTLN ("********** calculation ends ***********");};

The above program just handles an exception in the code, if there are multiple exceptions?

Modify code, enter values for I and J by initializing parameters

public class Exceptiondemo04{public static void Main (String args[]) {System.out.println ("********** calculation begins ***********"); int i = 0;//define integer variable int j = 0;//define integer variable try{string str1 = args[0];//Receive first argument String str2 = args[1];//Receive second parameter i = Integer. parseint (STR1);//Convert the first argument from a string to integer j = integer.parseint (str2);//Change the second argument from string to int temp = i/j;//The exception is generated here System.out.print ln ("The result of dividing two numbers:" + temp); System.out.println ("----------------------------");} catch (ArithmeticException e) {//Catch arithmetic exception System.out.println ("An exception occurred:" + e);} SYSTEM.OUT.PRINTLN ("********** calculation ends ***********");};
Enter a valid parameter: 10 2


At this point the data is actually given to the user input, since it is user input, it is possible to enter the incorrect, in fact, the above code has three problems:

1, if there is no input parameters or input parameters are not enough, there will be problems:


Array exceeded binding because no input parameters

2, if the input parameters are not numbers, but letters;


3, arithmetic anomalies, if the divisor is 0


So the above procedure produces three more obvious anomalies:

Array exceeded binding: arrayindexoutofboundsexception

Numeric format exception: NumberFormatException

Arithmetic exception: ArithmeticException

If you want the program to perform correctly, you must handle three exceptions at the same time, so you need three catch statements at this point.

public class Exceptiondemo05{public static void Main (String args[]) {System.out.println ("********** calculation begins ***********"); int i = 0;//define integer variable int j = 0;//define integer variable try{string str1 = args[0];//Receive first argument String str2 = args[1];//Receive second parameter i = Integer. parseint (STR1);//Convert the first argument from a string to integer j = integer.parseint (str2);//Change the second argument from string to int temp = i/j;//The exception is generated here System.out.print ln ("The result of dividing two numbers:" + temp); System.out.println ("----------------------------");} catch (ArithmeticException e) {//Catch arithmetic exception//SYSTEM.OUT.PRINTLN ("Arithmetic exception:" + E); E.printstacktrace ();} catch (NumberFormatException e) {//Capture number Conversion exception System.out.println ("Numeric conversion exception:" + E);} catch (ArrayIndexOutOfBoundsException e) {//capture array out of bounds exception System.out.println ("Array Out of Bounds exception:" + E);} SYSTEM.OUT.PRINTLN ("********** calculation ends ***********");};

In a very small program, there will be three exceptions, of course, there may be other exceptions, then the process will be very troublesome.

Exception inheritance knot structure:

In the entire Java exception structure, there are actually the following two most commonly used classes: Exception, Error, these two classes are throwable subclasses.

Exception: Generally represents a problem in the program, you can directly use the Try...catch processing.

Error: General refers to a JVM error that cannot be handled in the program.


In general, developers are more accustomed to the error and exception referred to as exceptions, and some of the previous processing of the exception, are exception subclasses.

Attention:

In general, when outputting exception information, you can print the exception object directly using System.out.println ().

You can also provide a method through exception: public void Printstacktrace ()

exception handling Mechanisms in Java

In the entire Java exception handling, it is actually handled in an object-oriented manner, the steps are as follows:

Once an exception is generated, an instantiated object of the exception class is generated first:

To capture this exception object in a try statement:

The resulting exception object matches the individual exception types in the Catch statement and executes the code in the catch statement if the match succeeds.


Review the polymorphism of an object: An instantiated object of a subclass can be received directly using the object of the parent class.

This concept is actually used in exception handling, because a try produces an instantiated object. If there are some other exceptions that you do not know, you can use exception to capture them at the end.

public class Exceptiondemo06{public static void Main (String args[]) {System.out.println ("********** calculation begins ***********"); int i = 0;//define integer variable int j = 0;//define integer variable try{string str1 = args[0];//Receive first argument String str2 = args[1];//Receive second parameter i = Integer. parseint (STR1);//Convert the first argument from a string to integer j = integer.parseint (str2);//Change the second argument from string to int temp = i/j;//The exception is generated here System.out.print ln ("The result of dividing two numbers:" + temp); System.out.println ("----------------------------");} catch (ArithmeticException e) {//Catch arithmetic exception//SYSTEM.OUT.PRINTLN ("Arithmetic exception:" + E); E.printstacktrace ();} catch (NumberFormatException e) {//Capture number Conversion exception System.out.println ("Numeric conversion exception:" + E);} catch (ArrayIndexOutOfBoundsException e) {//capture array out of bounds exception System.out.println ("Array Out of Bounds exception:" + E);} catch (Exception e) {System.out.println ("other exception:" + E);} SYSTEM.OUT.PRINTLN ("********** calculation ends ***********");};

Note: In exception handling, catch a thicker exception after catching a finer exception.

For example, the following procedure is wrong.

public class Exceptiondemo07{public static void Main (String args[]) {System.out.println ("********** calculation begins ***********"); int i = 0;//define integer variable int j = 0;//define integer variable try{string str1 = args[0];//Receive first argument String str2 = args[1];//Receive second parameter i = Integer. parseint (STR1);//Convert the first argument from a string to integer j = integer.parseint (str2);//Change the second argument from string to int temp = i/j;//The exception is generated here System.out.print ln ("The result of dividing two numbers:" + temp); System.out.println ("----------------------------");} catch (Exception e) {System.out.println ("other exception:" + E);} catch (ArithmeticException e) {//Catch arithmetic exception//SYSTEM.OUT.PRINTLN ("Arithmetic exception:" + E); E.printstacktrace ();} SYSTEM.OUT.PRINTLN ("********** calculation ends ***********");};


Since all exception objects can be received using exception (all can happen up), wouldn't it be more convenient to use exception directly?

public class Exceptiondemo08{public static void Main (String args[]) {System.out.println ("********** calculation begins ***********"); int i = 0;//define integer variable int j = 0;//define integer variable try{string str1 = args[0];//Receive first argument String str2 = args[1];//Receive second parameter i = Integer. parseint (STR1);//Convert the first argument from a string to integer j = integer.parseint (str2);//Change the second argument from string to int temp = i/j;//The exception is generated here System.out.print ln ("The result of dividing two numbers:" + temp); System.out.println ("----------------------------");} catch (Exception e) {System.out.println ("other exception:" + E);} SYSTEM.OUT.PRINTLN ("********** calculation ends ***********");};
Of course all the exceptions are handled in the same way that you can use the above form to capture directly using exception. Of course, it is not recommended to use this in a more detailed development, and all exceptions are best captured separately.

Problem:

Since capturing exception is the most convenient, then the direct capture of Throwable is not OK?

First of all, this is possible, but normal developers will not do this, because in a try in the program will always throw exception subclasses, and Throwable not only have exception and error.

Summary of the concept of anomalies:

1, after the exception occurs, if there is no reasonable treatment, then the entire program will be interrupted to execute.

2. Use Try...catch and try...catch...finally to handle exceptions, and finally will act as the uniform egress for the exception, and this statement will be executed regardless of whether or not there is this exception.

3. There can be multiple catches at the same time in an exception handling, but catching a thicker exception should be placed after a finer exception, or the program will compile with an error.

4, in the exception of the largest class is Throwable, divided into two sub-categories: Exception, Error.

Exception: Is an exception that the program can handle itself.

Error: Indicates JVM errors, general procedures cannot handle.

5, capture the time can be directly captured exception, but it is best to capture separately, if all the exception after the processing operations are the same, you can also directly capture the exception.

6. Whenever an exception is generated, an instantiated object of an exception class is generated in the program, which is then used to match the exception type in the catch, if the match succeeds, the contents of the Catch statement are executed, if the match is unsuccessful, the match continues downward, and if none succeeds, There is an issue with interrupt execution in the program.

an in-depth study of anomaliesKey points of research: Mastering the function of throws and throw keyword, mastering the difference between exception and runtimeexception, can customize exception class, understand the function of assertion and application. throws keyword: When defining a method you can use the throws keyword declaration, using the method declared by throws to indicate that this method does not handle the exception, but instead gives it to the call to process. throws format for usePublic return value type method name (parameter list ...) Throws Exception class {}Suppose a method of dividing (div ()) is defined, and it is possible for a division operation to have an exception, possibly without an exception, so it is best to use the throws keyword declaration for such a method, and once an exception occurs, it should be handled at the call. At this point, if you call this class of div method, you must do exception handling.

The class math{public int div (int i,int j) throws exception{//defines the division operation, and if there is an exception, it is given the handle int temp = i/j;//calculation, but there may be an exception return here temp;}}; public class Throwsdemo01{public static void Main (String args[]) {Math m = new Math ();//Instantiate the Math class object Try{system.out.println ( "Division operation:" + M.Div (10,0));} catch (Exception e) {e.printstacktrace ();//Print Exception}}};

Note: If an exception is not caught at the call, an error will occur at compile time

What if the throws keyword is now used in the declaration of the main method? Does that mean that the main method can also not handle exceptions?

The class math{public int div (int i,int j) throws exception{//defines the division operation, and if there is an exception, it is given the handle int temp = i/j;//calculation, but there may be an exception return here temp;}}; public class throwsdemo02{//all exceptions in the main method can be handled without using Try...catch public static void Main (String args[]) throws exception{ Math m = new Math ();//Instantiate the Math class object System.out.println ("division operation:" + M.Div (10,0));}};

In this program the main method does not handle any exceptions, but to the largest head, Java is the largest header is the JVM, so if the main method used the throws keyword, it means that all exceptions to the JVM for processing, the default processing is also done using the JVM.

Throw keyword:

The Throw keyword is a function of throwing an exception in the program. Thrown when thrown is an instantiated object of an exception class.

Unlike throws, you can throw an exception directly using throw. Throws an instantiated object of the exception class directly.

In the exception handling, the Try statement is to catch an exception object, then the exception object can also throw itself.

public class Throwdemo01{public static void Main (String args[]) {try{throw new Exception ("Throw yourself in the game.") The instantiated object}catch (Exception e) {System.out.println (e);}}};

Example: application of throw and throws

In the general development of try...catch...finally, throw, throws joint use of the situation is the most, for example: now to design a division method, but before the operation must print the "Calculate Start" information, after the end must print "End of the exception" information, If there is an exception, you should give the exception to the call processing, in the face of such requirements, you must use all of the above operations.

The class math{public int div (int i,int j) throws exception{//defines the division operation, and if there is an exception, it is transferred to the manipulated System.out.println ("* * * * * * * * * * * * * * * *)"; int temp = 0;//define local variable try{temp = i/j;//calculation, but there may be an exception}catch (Exception e) {throw e;} finally{//the Uniform Export System.out.println ("* * * * * * * * * * * * * * * *), whether or not it is abnormal;} return temp;}; public class Throwdemo02{public static void Main (String args[]) {Math m = new Math (); Try{system.out.println ("Division operation:" + M.di V (10,0));} catch (Exception e) {System.out.println ("exception generated:" + E);}};


Note: If an exception occurs, the following action will not be performed if it is not placed inside the finally block.

The difference between exception and runtimeexception

is a recurring problem in a Java interview

Observe the following code:

public class Runtimeexceptiondemo01{public static void Main (string args[]) {string str = "123";//define string, all of which consist of numbers int temp = Integer.parseint (str); Change the string to the int type SYSTEM.OUT.PRINTLN (temp * temp);//Compute-exponentiation}};
The parseint () method defines the format:

parseint (String s)                    Throws NumberFormatException
In this method obviously use the throws keyword throws an exception, why do not have to deal with, compile also can pass?

Exception and RuntimeException

The differences between the two classes are as follows:

Exception must be handled in the program using Try...catch

The runtimeexception can be processed without try...catch, but if there is an exception, the exception is handled by the JVM.


In the exception handling mechanism of Java:

If the type of exception is thrown, it must be handled using Try...catch.

If the type of runtimeexception is thrown, it is not necessary to use try...catch for processing, once an exception will be processed by the JVM, but in order to ensure the health of the program, it is recommended to be honest in the case where there is an exception. catch to handle.

Custom Exception classes:

You can complete a custom exception class only if you inherit exception. Because the standard exception classes are provided in Java (including some exception information, etc.), you can customize the exception class if you need to define the exception information you want.

Just inherit the exception class directly.

Class MyException extends exception{//custom exception class, inheriting Exception class public myexception (String msg) {super (MSG);// Call a constructor that has a parameter in the exception class, pass the error message}};p ublic class Defaultexception{public static void Main (String args[]) {Try{throw new MyException ("Custom exception. ") ; Throw exception}catch (Exception e) {System.out.println (e);}}}

Generally if the project is very large, it is possible to customize the exception, you can get some accurate information and so on.

Assertion: (Assert)

After JDK1.4, the assertion function is added in Java, so what is assertion? The assertion is that the return value of a result is correct, and if the return value of the result is incorrect, the assertion check will definitely prompt the user for the error message. The definition format for assertions is as follows:

An assert Boolean expression;

Assert Boolean expression: detailed information;

public class Test{public static void Main (String args[]) {int x[] = {};//definition array, length 3assert x.length==0: "Array length not 0";// The length of the assertion array here is 0}};

The assertion itself does not affect the execution of the program, but if you want to make an assertion work, you must validate the assertion.

The assertion is verified as follows:

After compiling the DOS command, use JAVA-EA test

Verify the steps in MyEclipse: Select the program, and right-click Add-ea in the Run as->run configurations->vm arguments.


Summarize:

1, the assertion in the actual development is not very common, simple understanding can be.

2, throw and throws keyword joint use problem

Throw: Throw Exception object

Throws: Used at the declaration of a method to indicate that this method does not handle exceptions.

3, exception the exception must be handled, and runtimeexception exception can not be processed, but in order to ensure that the program runs, as long as there are exceptions best all processing.

4, if you need to customize the exception, then directly inherit the exception class can be




Exception Handling in Java

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.