1. Differences
Throws is used to declare all the exception information a method might throw , throws is to declare the exception but not to handle it, but instead to upload the exception, and whoever calls me will handle it. A throw is a specific type of exception thrown.
2. Introduce respectively
Throws: Used to declare an exception, for example, if a method does not want to have any exception handling, then in the absence of any code for exception handling, the method must be declared all possible exceptions (in fact, do not want to do their own work, then to others, tell others I will appear what abnormal, Report your own mistakes and let others handle them.
The format is: Method name (parameter) throws Exception Class 1, Exception Class 2, .....
1 classmath{2 Public intDivintIintJthrowsexception{3 intt=i/J;4 returnT;5 }6 }7 8 Public classThrowsdemo {9 Public Static voidMain (String args[])throwsexception{TenMath m=NewMath (); OneSystem.out.println ("Start Operation:" +m.div (10,2)); A } -}
Throw: The exception is handled by itself, there are two ways to handle it, either catch the exception yourself (that is, try catch to catch), or declare throw an exception (that is, throws exception ~ ~).
Attention:
Once the throw is executed, the program is immediately transferred to the exception handling phase, and the subsequent statement is no longer executed, and the method no longer returns a meaningful value!
1 Public classTestthrow2 {3 Public Static voidMain (string[] args)4 {5 Try6 {7 //calling a method with the throws declaration must explicitly catch the exception8 //Otherwise, the throw must be declared again in the Main method9Throwchecked (-3); Ten } One Catch(Exception e) A { - System.out.println (E.getmessage ()); - } the //calling the method that throws the runtime exception can either explicitly catch the exception, - //You can also ignore the exception -Throwruntime (3); - } + Public Static voidThrowchecked (intAthrowsException - { + if(A > 0) A { at //self-throwing exception exception - //the code must be in a try block, or in a method with a throws declaration - Throw NewException ("A has a value greater than 0, does not meet the requirements"); - } - } - Public Static voidThrowruntime (inta) in { - if(A > 0) to { + //self-throwing runtimeexception exception, which can be explicitly caught by the exception - //You can also ignore the exception completely and give the method caller the exception to handle the Throw NewRuntimeException ("A has a value greater than 0, does not meet the requirements"); * } $ }Panax Notoginseng}
The difference between throw and throws in Java exception handling