Java Exception Handling

Source: Internet
Author: User
Tags finally block getmessage try catch log4j

Exception handling:

Java exception handling keywords are: Try Catch finally throw throws

The error is not an exception, but a problem that is out of the programmer's control, and all exception classes are subclasses that inherit from the Java.lang.Exception class.

The cause of the exception usually includes:

The user has entered illegal data

The file you want to open does not exist

The connection is interrupted during network communication, or the JVM memory overflows.

Syntax for the TRY Catch structure:

 Public classTest { Public Static voidMain (string[] args) {Try{Scanner in=NewScanner (system.in); System.out.print ("Please enter dividend:"); intNUM1 =In.nextint (); System.out.print ("Please enter the divisor:"); intnum2 =In.nextint (); System.out.println (String.Format ("%d/%d =%d", NUM1, num2, Num1/num2)); System.out.println ("Thanks for using this program!" "); } Catch(Exception e) {System.err.println ("Generated Abnormal Information" +e.getmessage ());//e.getmessage () Get Exception section information} System.out.println ("Code after the try Catch block"); }    }

It should be noted that in the example above, when the divisor is 0 o'clock, the program produces an exception. The code that follows the try catch block will output normally. The result of the program operation is:

Please input dividend: 2 Please enter the divisor:0 generates an exception message /By the code behind the zerotry catch block

E.getmessage () to get the exception part information. In this case, the output is:/by zero

Try and catch and finally structure

     Public Static voidMain (string[] args) {Try{Scanner in=NewScanner (system.in); System.out.print ("Please enter dividend:"); intNUM1 =In.nextint (); System.out.print ("Please enter the divisor:"); intnum2 =In.nextint (); System.out.println (String.Format ("%d/%d =%d", NUM1, num2, Num1/num2)); System.out.println ("Thanks for using this program!" "); } Catch(Exception e) {}finally{System.out.println ("Here is the finally block"); }    }

It is important to note that the only thing that does not run finally is to exit the JVM, which is system.exit (0); When there is a return in the catch statement, run finally and finally execute the return statement. Finally, the code is executed regardless of whether an exception is generated. In the example above, the result is:

Please input dividend: 4 Please enter the divisor:0 Here is the finally block

Multiple Try Catch blocks

The multiple try Catch block has the following characteristics: The order of the catch statements: the subclass stepfather class, the order by which the exception occurs, and only the first catch statement that matches the exception type is executed. The syntax structure is:

 Try{ 
//Program code
}Catch(Exception type1The variable name of the exception1){
     //Program code
}catch ( Exception type 2 exception variable name 2) Span class= "Hl-brackets" >{
// program code Span class= "hl-comment" >
}catch< Span class= "Hl-brackets" > ( exception type 2 exception variable name 2) {
// program code
}

Throws/throw keywords

If a method does not capture an inspection exception, the method must be declared using the throws keyword. The throws keyword is placed at the tail end of the method signature. You can also throw an exception with the Throw keyword, whether it's newly instantiated or just captured. In the next instance, a Remotexception exception is thrown, a method can declare multiple exceptions, and multiple exceptions are separated by commas.

 Public class classname{  publicvoid deposit (doublethrows  remoteexception  {       thrownew  remoteexception ();  }}

There are the following considerations when handling exceptions: Catch cannot exist independently of a try. Adding a finally block after Try/catch is not mandatory. The try code cannot have neither a catch block nor a finally block. You cannot add any code between try, catch, finally block.

Memory: (Common type of exception)

Exception: Parent class for exception hierarchies

ArithmeticException: Arithmetic error case, such as dividing by zero

ArrayIndexOutOfBoundsException: Array subscript out of bounds

NullPointerException: Attempting to access a null object member

ClassNotFoundException: Unable to load the required classes

Iiiegalargumentexception: Method received illegal parameter

ClassCastException: Object coercion; type conversion error

NumberFormatException: Numeric format conversion exception, such as converting "ABC" to Digital

Log

To import a jar package, the following instance creates a log object and then stores the exception information and displays it to the console:

 Public Static voidMain (string[] args) {//Create a Log objectLogger Logger=logger.getlogger ("Testing class test"); Scanner input=NewScanner (system.in); Try{System.out.println ("Please enter dividend"); intA =Input.nextint (); System.out.println ("Please enter a divisor"); intb =Input.nextint (); System.out.println ("Result:" + A/b); } Catch(ArithmeticException e) {//Log store error messageLogger.debug ("Divisor cannot be 0"); }        Catch(Exception e) {//Log store error messageLogger.debug ("Input is not a number"); }    }

Log4j.properties configuration File Source code is:

# # # Set Logger output level and output Destination # # #log4j. Rootlogger== = =%p%d{yyyy-mm-dd hh:mm : SS SSS}%l%m%n### output log information to file: Jbit.log # # #log4j. appender.logfile=  Org.apache.log4j.FileAppenderlog4j.appender.logfile.File=jbit.loglog4j.appender.logfile.layout= Org.apache.log4j.PatternLayoutlog4j.appender.logfile.layout.ConversionPattern=%d{yyyy-mm-dd hh:mm:ss}% L%F%p%m%n

The output is:

Please enter dividend , enter the divisor 02018-03-28 19:11:08 639 com.log.Test.main (test.java:21) divisor cannot be 0

Log files record exception information in real time:

2018-03-28 17:31:04com.log.test.main (test.java:25) Test.java DEBUG  Input not the number 2018-03-28 18:18:39com.log.test.main (test.java:21) Test.java DEBUG  divisor cannot be 02018-03-28 19:11:08com.log.test.main ( test.java:21) Test.java Debug  divisor cannot be 02018-03-28 19:11:56com.log.test.main (test.java:21) Test.java Debug  the divisor cannot be 0

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.