Previous | Home | Next |
Throws statement throw exception explicitly. if a method does not handle a checked exception, the method must declare it using the throw keyword. Exception throws as throw.
Throw throwableInstance
Throwableinstance must be object of throwable class or of it's sub class. This object will be caught using catch clause. After throw statement flow of excution stop immediately and switch to nearest catch statement. if it doesn't find any catch then default handler of halts the program and print stack trace.
Example
/* * Save as useThrow.java * Using throw */ package usingthrow; class throwDemo{ public void throwmeth ( ) { try { throw new IllegalStateException(); } catch (NullPointerException e) { System.out.println("Not Caught by the catch block inside throwmeth"); } } } public class useThrow { public static void main(String[] str) { try { throwDemo obj =new throwDemo(); obj.throwmeth(); } catch(IllegalStateException e) { System.out.println("Exception Caught in main "+ e); } } }
Output:
Exception Caught in main java.lang.IllegalStateException
Previous | Home | Next |