Syntax of throw keyword-
throw ExceptionClassObject;
Example
throw new FileNotFoundException("File is not present");
void aMethod() throws FileNotFoundException{ //code throw new ClassNotFoundException(); }
The above code will give compile time error as ClassNotFoundException is not a subclass of FileNotFoundException.
When a method declares to throw an exception, in that case, you can do any one of the followings-
import java.io.*; class Test { public static void show() throws FileNotFoundException { throw new FileNotFoundException("File does not exist"); } public static void main(String args[]) { try { show(); } catch(FileNotFoundException e) { System.out.println("Exception is handled"); } System.out.println("Normal flow"); } }
Output
Exception is handled Normal flow
import java.io.*; class Test { public static void show() throws FileNotFoundException { throw new FileNotFoundException("File does not exist"); } public static void main(String args[]) throws FileNotFoundException { show(); System.out.println("Normal flow"); } }
Output
Runtime Exception