The throwable class is the parent class of all Exception classes.
Runtimeexception inherited from throwable
In the JDK document
Meaning:
Previously, throw an exception when writing code,
Some exceptions are not required by the throws Statement (after the method declaration), while some must be followed by the throws Statement ),
Or try .. catch (in the method body ).
For more information, see post: http://bbs.csdn.net/topics/390279427
Let's look at a small example.
Receive the two int types entered in the console, and then divide the two.
Package it. mark; import Java. util. extends; public class onexceptiondemo {public static void main (string [] ARGs) {usingdivisioncalcu () ;}/ *** use the Division calculator to calculate the value. */Private Static void usingdivisioncalcu () {int [] input = new int [2]; // create sequence object sequence scan = new sequence (system. in); // wait for the user to enter while (scan. hasnextint () {for (INT I = 0; I <2; I ++) {input [I] = scan. nextint ();} break;} // obtain the divisor and divisor from user input data. Int dividend = input [0]; int divisor = input [1]; calc4division (dividend, divisor);}/*** Division calculation. ** @ Param dividend * divisor */Private Static void calc4division (INT dividend, int divisor) {int result = 0; Result = dividend/divisor; system. out. println ("Calculation Result:" + result );}}
Obviously, a division of 0 is incorrect.
Modify the calc4division method.
/*** Division calculation. ** @ Param dividend * divisor */Private Static void calc4division (INT dividend, int divisor) {int result = 0; If (divisor = 0) {Throw new arithmeticexception ("the divisor is 0 and does not comply with human computing rules! ") ;}Result = dividend/divisor; system. Out. println (" Calculation Result: "+ result );}
It can be seen that throw arithmeticexception is abnormal in method calc4division,
However, the compiler does not require throws or try... catch.
If you change to exception or its subclass, the compiler will ask you.
Here, we can directly capture
/*** Division calculation. ** @ Param dividend * divisor */Private Static void calc4division (INT dividend, int divisor) {int result = 0; try {result = dividend/divisor;} catch (arithmeticexception AE) {system. out. println ("the divisor is 0 and does not comply with human computing rules! "+ AE. getmessage ();} system. Out. println (" Calculation Result: "+ result );}
Last reminder
If throw runtimeexception occurs in your code, you need to handle it according to the actual situation.
It is up to you to decide whether to capture or let him run an error!
More aboutTry catch
YesGo --->
Http://blog.csdn.net/androidbluetooth/article/details/7868521