Throwable is all exceptions of course super Class! The two direct subclasses of the class are error and exception.
Eroor:java Run-time internal error and resource exhaustion error, hard to recover!
Exception: Can be easily divided into two categories: 1.RuntimeException: abnormal operation; 2. Non-runtimeexception: caused by environmental factors;
Exception handling and getting exceptions:
try{
Put the function that might be wrong in here
}catch (Exception e) {
Processing methods
}finally{
This code executes whether or not an error occurs
}
In catch we usually write exception catch all exceptions
When an exception occurs in a try, the code immediately executes the code in the catch, where we call E.getmassage () if we want to print the exception information, or directly by calling the E.printstacktrace () method, which directly prints the exception
Example 1: An exception occurs when a string is entered, or if the entry is 0 o'clock. So the call to the Shuru method must be try{}catch{}; If you don't want to try{}catch{}, you have to declare it before you throw this exception (throws Exception), and then who calls this method who will handle it!
PackageCom.inba.maya.huoquyichang;ImportJava.util.*; Public classHuoquyichang { Public Static voidmain1 (string[] args) {Huoquyichang h=NewHuoquyichang (); Try{H.shuru (); }Catch(Exception e) {System.out.println (E.getmessage ()); } } Public voidShuru ()throwsexception{System.out.println ("Please enter:"); Scanner SC=NewScanner (system.in); String s=Sc.nextline (); intnum=Integer.parseint (s); DoubleZ=100/num; System.out.println (z); } }
Example 2:
PackageCom.inba.maya.huoquyichang;ImportJava.util.*; Public classHuoquyichang { Public Static voidmain2 (string[] args) {intNum=0; System.out.println ("Please enter:"); Try{Scanner sc=NewScanner (system.in); String s=Sc.nextline (); Num=Integer.parseint (s); }Catch(Exception e) {System.out.println ("The input must be a number" +e.getmessage ()); Throwe; } DoubleZ; Try{z=100/num; }Catch(Exception e) {System.out.println ("The input cannot be 0" +e.getmessage ()); } }}
Principle of Exception use:
1. Do not use the exception too much to meet the burden of the system.
2. When you use the try{}catch{} statement block in a method to catch an exception, you must handle the exception.
3.try{}catch{} statement block is not too large, which is not conducive to the analysis of the exception.
4. When a method is overwritten, the method that overrides it must throw the same exception or child exception
Exception: the classification of exceptions; getting exceptions and handling; throwing exceptions