Java Handling Exception __java

Source: Internet
Author: User
Tags exception handling stack trace throw exception

Use try-catch or try-catch-finally in Java to catch and handle exceptions.

First, about Try-catch

Basic syntax

Try
{
  //need to be detected code
}
catch (Exception class variable)
{
 //processing mode
}

What happens if the code in the try block throws an exception. The method that throws the exception terminates execution, and the control of the program is handed over to the exception handler in the Catch block, so how is the code in the catch block written? You can warn users or programmers to check for configuration, network connections, and log error logs in catch statement blocks. However, if no exception occurs, the catch code block is not executed.

How to catch Exception code samples (single type exception):

        try{
            System.out.println ("Please enter your Age:");

            Scanner Scanner = new Scanner (system.in);

            int age = Scanner.nextint ();

            System.out.println ("After ten years Your age is:" +age+10);

        } catch (Inputmismatchexception e) {

            System.out.println ("You should output an integer!!");
        }

        SYSTEM.OUT.PRINTLN ("program over");

Test results:

Please enter your age:
15.2
You should output an integer!!
The program's over.

Note: After the Try-catch block has finished executing, the code behind it will continue to execute.

How to catch Exception code samples (multiple types of exceptions): Multiple catch blocks catch multiple types of exceptions, respectively.

        try{
        Scanner input = new Scanner (system.in);
        SYSTEM.OUT.PRINTLN ("Please output first number:");
        int one = Input.nextint ();
        SYSTEM.OUT.PRINTLN ("Please output second number:");
        int two = Input.nextint ();
        SYSTEM.OUT.PRINTLN ("The result of dividing two numbers is:" +one/two);

        The input mismatch exception
        }catch (Inputmismatchexception e) {

            System.out.println ("You should enter an integer");

       Arithmetic exception
        }catch (ArithmeticException e) {

            System.out.println ("divisor cannot be 0");
        } catch (Exception e) {

            SYSTEM.OUT.PRINTLN ("Unknown Error");
        }

        SYSTEM.OUT.PRINTLN ("program run Over");

Test results:

Please output the first number:
ten
Please output the second number:
0
Divisor can not be 0
program run end

Write multiple catch blocks to follow: first specific, after General (first subclass Hofu Class)
This is because when an exception occurs, the exception handler looks for a matching exception handler nearby, and the subclass inherits from the parent class, and the exception handler for the parent class is also applicable to the subclass.

Ii. about try-catch-finally
Basic syntax

try{
//Some methods that throw an exception
}catch (Exception e) {
//code block to handle the exception
}catch (Exception 2e) {
//code block handling the exception
} ... (n catch blocks) ... {
...
} finally{
//FINAL code to be executed
}

Regardless of whether the program has an exception, the contents of the finally statement block are executed, which allows the program to be robust, regardless of the steps that must be performed in any case.

To see a finally example, define the following methods

/**
     * Divider (DIVISOR)
     * result (Results)
     *  try-catch not while loop
     *  Each loop, divider minus 1,result = effect +100/ Divider
     *  if: Catch exception, print output, throw exception, and return 999
     *  Otherwise, return resul
     *  finally  : this is Finally, The value of the printout result is also
     * *
    /public int test2 () {
        int divider = ten;
        int result =;
        try{while

            (Divider >-1) {
                divider--;
                result = result +100/divider;
            }
            return result;

        } catch (Exception e) {
            //Output The exception's trace stack information to the standard error output
            e.printstacktrace ();
            System.out.println ("Throw out an exception");
            return result = 999;

        } finally{

            System.out.println ("This is finally,result value =" +result);
        }
    

Output results:

Attention:
1 finally statement block in Try-catch-finally, which is executed before returning to the caller after the execution of the RERUTRN statement in the try and catch statement block is completed .
2 If there is no return statement within the try-catch-finally, then the statement outside the 3 statement block will be invoked
3) fially statement blocks generally put some of the code to release resources. For example, when an exception occurs while manipulating data, the database connection is finally closed

Third, access to exception information

If a Java application wants to access information about an exception object in a catch block, it can be obtained by invoking a method that has an exception parameter for the catch.

All exception objects in Java contain the following common methods:

1, GetMessage (): Returns the detailed description string for the exception

For example:/by zero

2, toString () exception Name: Exception information

Example: Java.lang.ArthmeticException:/by zero

2,printstacktrace () : The exception of the tracking stack information output to the standard error output include: Exception name, exception information, the location of the occurrence of the exception the return value of this method is void.

In fact, the default exception handling mechanism of the JVM is to call Printstacktrace () and print the stack trace of the exception.

For example:

Java.lang.ArithmeticException:/by zero in
    com.lemon.FinallyTest.test2 (finallytest.java:54)
    at Com.lemon.FinallyTest.main (finallytest.java:119)

Demo Address: http://download.csdn.net/download/qq_18505715/9865121

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.