If a method can cause an exception but does not handle it, it must specify this behavior so that the callers of the method can protect themselves without exception. Do that. You can include a throws clause in a method declaration. A throws clause lists all the exception types that a method might throw. This is necessary for all exceptions of type except error or runtimeexception and their subclasses. All other types of exceptions that a method can throw must be declared in the throws clause.Failure to do so will result in a compilation error。
The following is a common form of a method declaration that contains a throws clause:
Type Method-name (parameter-list) throws exception-list{
Body of method
}
Over hereexception-listIs the list of exceptions that the method can throw with a comma-separated exception.
The following is an incorrect example. This example attempts to throw an exception that it cannot catch. Because the program does not specify a throws clause to declare the fact, the program will not compile.
This program contains an error and would not compile.
Class Throwsdemo {
static void Throwone () {
System.out.println ("Inside throwone.");
throw New Illegalaccessexception ("demo");
}
public static void Main (String args[]) {
Throwone ();
}
}
To compile the program, you need to change two places. First, declare Throwone () to throw a Illegalaccess exception exception. Second, main () must define a Try/catch statement to catch the exception. The correct examples are as follows:
This was now correct.
Class Throwsdemo {
static void Throwone () throws Illegalaccessexception {
System.out.println ("Inside throwone.");
throw New Illegalaccessexception ("demo");
}
public static void Main (String args[]) {
try {
Throwone ();
} catch (Illegalaccessexception e) {
System.out.println ("caught" + e);
}
}
}
The following is an example of the output:
Inside Throwone
Caught Java.lang.IllegalAccessException:demo
How is the Java throws clause written?