Java Exception Handling Mechanism (2)
1. Role of throw
Class Usre {
Private int age;
Public void setAge (int age ){
If (age <0 ){
RuntimeException e = new RuntimeException ("Age cannot be negative"); // generate an exception object
Throw e; // throw
}
This. age = age;
}
}
Class Test {
Public static void main (String args []) {
User user = new User ();
User. setAge (-20 );
}
}
Throw is used to throw an exception object.
2. Role of throws
Class Usre {
Private int age;
Public void setAge (int age) throws Exception {
If (age <0 ){
Exception e = new Exception ("Age cannot be negative"); // generate an Exception object
Throw e; // throw
}
This. age = age;
}
}
Class Test {
Public static void main (String args []) {
User user = new User ();
Try {
User. setAge (-20 );
}
Catch {
System. out. println (e );
}
}
}
Throws: When an exception may occur in a function, you can use try... catch can handle code that may generate exceptions. It can also be declared after the function to generate an Exception (declaration method: add the possible Exception type after throws). Once declared, therefore, this function has no responsibility to handle this exception, but to handle this exception from the called place.