In the process of programming, we often encounter this situation, in the current environment can not be resolved, such as user-passed parameter errors, IO device problems. At this point, the exception to be thrown from the current environment is submitted to the superior for processing.
In the Java language, use the throw keyword to throw an exception. Look at the following code
Public classa**Exception {PrivateString ID; Public voidSetID (String id) {if(id.length () = =7) { This. ID =ID; }Else { Throw NewIllegalArgumentException ("parameter length is not 7 bits"); } } }
Above the code, we throw an exception of type illegalargumentexception.
declaring exceptions
If an exception is thrown in a method body, we want the caller to be able to catch the exception. So, how do you tell the caller?
In the Java language, the throws keyword declares an exception that a method might throw, and in the above code we throw a illegalargumentexception type of
Abnormal. You can let the caller know what kind of exception the method is likely to have and catch it in time by doing the following:
Public classa**Exception {PrivateString ID; //use the throws keyword to declare possible exceptions to this method Public voidSetID (String id) throws Illegalexception {if(id.length () = =7) { This. ID =ID; } Else { Throw NewIllegalArgumentException ("The parameter length should be 7"); } } }
JAVA throws and declares exceptions