To throw an exception explicitly, using the throw statement.
The general form of throw is shown here:
throw ThrowableInstance;
Here, ThrowableInstance
must be an object of type Throwable or a subclass of Throwable.
To get a Throwable object: using a parameter in a catch clause or creating one with the new operator.
The flow of execution stops after the throw statement and any subsequent statements are not executed.
public class Main { public static void main(String[] args) { try {/*from ww w .j av a 2 s . c o m*/ throw new Exception("test"); } catch (Exception e) { System.out.println(e); } } }
// Demonstrate throw. public class Main { static void myMethod() { try { /*from w w w.j a va 2 s .co m*/ throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside myMethod."); throw e; // rethrow the exception } } public static void main(String args[]) { try { myMethod(); } catch(NullPointerException e) { System.out.println("Recaught: " + e); } } }
To create one of Java's standard exception objects.
throw new NullPointerException("demo");