How to use a java try catch statement

Source: Internet
Author: User
Tags try catch

1) try catch finally in finally will be executed under any circumstances, and the execution time is before the program return.

2) the Java compiler does not allow display of statement blocks that cannot be executed. For example, after return, there may be no other statement blocks (the branches do not belong to this column). Therefore, the following program compilation

An error occurred while capturing the instance.

Public class MainClass {
Public static void main (String args []) {
Int d,;

Try {
D = 0;
A = 42/d;
System. out. println ("This will not be printed .");
} Catch (ArithmeticException e ){//
System. out. println ("Division by zero .");
    }
System. out. println ("After catch statement .");
  }
}

Try can have no catch, try can also be used with finally {}, but a try must have one of catch or finally.

Also, if you do not want to process it in this method, but process it together in the called method, you can directly add throws Exception after the method signature, that is, the parentheses after the method name, throwing exceptions to others

Instance

Import java. util. Random;

Public class MainClass {
Public static void main (String args []) {
Int a = 0, B = 0, c = 0;
Random r = new Random ();

For (int I = 0; I <32000; I ++ ){
Try {
B = r. nextInt ();
C = r. nextInt ();
A = 12345/(B/c );
} Catch (ArithmeticException e ){
System. out. println ("Division by zero .");
A = 0; // set a to zero and continue
      }
System. out. println ("a:" + );
    }
  }
}

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.