Java Throws Exception Statement Example
Chapter:
Exception Handling
Last Updated:
08-06-2017 14:04:15 UTC
Program:
/* ............... START ............... */
public class JavaThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) throws IllegalAccessException {
throwOne();
}
}
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);
}
}
}
/* ............... END ............... */
Output
Inside throwOne.Exception in thread "main"
java.lang.IllegalAccessException: demo
at ExceptionHandling.JavaThrowsDemo.throwOne(JavaThrowsDemo.java:20)
at ExceptionHandling.JavaThrowsDemo.main(JavaThrowsDemo.java:24)
Notes:
-
All Java methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. In the Java system, throwable objects are instances of any subclass of the Throwable.
- The Java throws keyword is used to declare an exception.
- All methods use the throw statement to throw an exception.
Tags
Java Throws, Exception Handling, Java