How much Java knows (the) use of try and catch

Source: Internet
Author: User
Tags stack trace

Although the default exception handlers provided by the Java Runtime system are useful for debugging, you typically want to handle exceptions yourself. There are two benefits to doing so. First, it allows you to fix errors. Second, it prevents the program from terminating automatically. Most users are annoyed at the end of the program's execution and the ability to print a stack trace whenever an error occurs (at least, so to speak). Fortunately, this is easy to avoid.

To prevent and handle a run-time error, just put the code you want to monitor into a try block. Immediately following the try block includes a catch clause that describes the type of error you want to capture. This is a simple task, and the following program contains a try block and a catch clause that handles the arithmeticexception exception caused by the 0 divide.
1 classExc2 {2      Public Static voidMain (String args[]) {3         intd, A;4         Try{//Monitor a block of code.5d = 0;6A = 42/D;7System.out.println ("This is not being printed."));8}Catch(ArithmeticException e) {//Catch Divide-by-zero Error9SYSTEM.OUT.PRINTLN ("division by zero."));Ten         } OneSystem.out.println ("After catch statement.")); A     } -}

The program output is as follows:

1 division by zero. 2 catch statement.

Note that the call to println () in the try block is never executed. Once an exception is thrown, program control is transferred from the try block to the catch block. Execution never "returns" from the catch block to the try block. Therefore, "This is not being printed." ”


Will not be displayed. Once the catch statement is executed, program control continues from the bottom line of the entire try/catch mechanism.

A try and its Catch statement form a unit. The scope of a catch clause is limited to the statement defined earlier in the Try statement. One catch statement cannot catch the exception that is thrown by another try declaration (unless it is a nested try statement condition).

Statement declarations that are protected by try must be within a curly brace (that is, they must be in a block). You cannot use try alone.

The purpose of constructing a catch clause is to resolve the exception condition and continue to run as if the error did not occur. For example, in the following program, each for loop is repeatedly given two random integers. The two integers are separated by each other, and the results are used in addition to 12345. The final result exists in a. If a division operation causes the error to be removed by 0, it is captured, the value of a is set to zero, and the program continues to run.
1 //Handle An exception and move on.2 ImportJava.util.Random;3 4 classHandleError {5      Public Static voidMain (String args[]) {6         intA=0, B=0, c=0;7Random r =NewRandom ();8 9          for(inti=0; i<32000; i++) {Ten             Try { Oneb =r.nextint (); Ac =r.nextint (); -A = 12345/(b/c); -}Catch(ArithmeticException e) { theSYSTEM.OUT.PRINTLN ("division by zero.")); -A = 0;//set A to zero and continue -             } -System.out.println ("A:" +a); +         } -     } +}

Show a description of an exception

Throwable overloads the ToString () method (defined by object), so it returns a string containing the description of the exception. You can display the description of the exception by passing an argument to the exception in println (). For example, the catch block of the preceding program can be rewritten as
1 Catch (ArithmeticException e) {2     System.out.println ("Exception:" + e); 3     // set A to zero and continue 4 }

When this version replaces the original version of the program, the program runs under the standard JAVAJDK interpreter, each of which is 0 apart from the error display the following message:

1     Exception:java.lang.ArithmeticException:/By zero

Although there is no special value in the context, the ability to display an exception description is valuable in other situations-especially when you experiment with and debug an exception.

Series Articles:

Java know how much (top)

Java know how much (interface) interface

Java knows how much (40) the difference between an interface and an abstract class

Java know how much (41) generic explanation

Java know how much (42) the range of generic wildcard characters and type parameters

Java know how much (43) Exception Handling Basics

Java know how much (44) exception type

Java know how much (45) uncaught exceptions

How much Java knows (the) use of try and catch

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.