The following is a java4android video tutorial from marschen.
Main content of this set.
1. Role of throw.
2. Role of throws
Instance.
In Java, everything has objects,
An exception is an object, so we can generate an exception object.
Use a class to generate.
The runtimeexception class initiated by JDK generates an exception.
Object ......
After an object is generated, it is thrown ....
Summary:
1. The role of throw. The JDK and Java virtual machine cannot judge it. We can use throw to throw an exception.
2. The role of throws. Declaring a function may cause an exception, but we will not handle it in this function,
And the exception try... catch... finally... is performed by the object that calls this function ....
Class user {private int age; Public void setage (INT age) throws exception {If (age <0) {// runtimeexception E = new runtimeexception ("Age cannot be negative "); uncheck exception // you can use uncheck exception for compilation. exception E = new exception ("Age cannot be negative"); // It is a check exception // It must be captured or declared. // Check exception cannot be compiled. There are two ways to compile it. // 1. try .... catch .... capture // 2. if throws is used for declaration, this function may produce exceptions but is not captured. Instead, it is captured by the object that calls this function. throw E;} This. age = age ;}}
Class test {public static void main (string ARGs []) {user = new user (); try {user. setage (-20); // There is no problem with the write syntax. // It is ridiculous. so we need to throw an exception .} catch (exception e) {system. out. println (e );}}}
Class user1 {private int age; Public void setage (INT age) {If (age <0) {system. out. println ("age <0"); try {exception E = new exception ("Try age cannot be negative"); throw E;} catch (exception e) {system. out. println ("catch age cannot be negative"); E. printstacktrace () ;}} this. age = age ;}}
Class test1 {public static void main (string ARGs []) {user1 user11 = new user1 (); user11.setage (-20 ); // There is no problem with writing the syntax in this way. // It is ridiculous. so we need to throw an exception .}}