Java throw keyword
throw Keyword
"We use throw keyword for customized exception handling purpose. We declare our own exception explicitly by using throw keyword. We can throw checked, unchecked and also user-defined exceptions."
Syntax Structure for throw keyword:
throw SubTypeThrowable Class;
The below demo program describes all the three types of exceptions thrown by using throw keyword explicitly.
Case I: Checked Exception
package com.navneet.javatutorial;
import java.io.IOException;
public class ThrowKeywordDemo {
public static void main(String[] args) {
try{
IOException e = new IOException();
throw e;
}
catch(IOException ex){
System.out.println("IO handling code");
}
}
}
Case 2: Unchecked Exception
package com.navneet.javatutorial;
public class UncheckedThrowExample {
public static void main(String[] args) {
ArithmeticException ae=new ArithmeticException("10/0");
throw ae;
}
}