throw an exception
in the previous article, we introduced the knowledge of catching exceptions. But you will certainly ask, since we can catch all sorts of anomalies, where are these exceptions thrown?
In the programming process, we often encounter this situation, in the current environment can not be resolved, such as user incoming parameter errors, IO device problems. At this point, the exception is thrown from the current environment and submitted to the superior for processing.
in the Java language, use the Throw keyword to throw an exception. Look at the following code Code:public class a**exception { private String id; public void SetID (string id) { if (Id.length () == 7) { this.id = id; }else { throw new illegalargumentexception ("parameter length is not 7 bits"); }     &NBSP} }
The above code, we throw a illegalargumentexception type of exception.
declaring an exception
If an exception is thrown in a method body, we want the caller to be able to catch the exception. So, how do you notify the caller?
In the Java language, the throws keyword declares an exception that a method might throw, in the above code we throw a illegalargumentexception type of
exception. By doing the following, you can let the caller know what kind of exception the method might have and catch it in time. Code:public class a**exception { private String id; //uses the throws keyword to declare an exception that may occur with this method public void setid (string id) throws Illegalexception { if (Id.length () == 7) { this.id = id; } else { throw new illegalarguMentexception ("parameter length should be 7"); }        &NBSP} }