Java - Throwing an Exception


You can also throw an exception in your code using a throw statement.


The syntax for a throw statement is

throw <A throwable object reference>;

throw is a keyword, followed by a reference to a throwable object.

A throwable object is an instance of a subclass of the Throwable class, or the Throwable class itself.

The following is an example of a throw statement, which throws an IOException:

// Create an object of IOException
IOException e1 = new IOException("File not found");
// Throw the IOException
throw e1;

You can also create a throwable object and throw it in one statement.

throw new IOException("File not found");



public class Main {

  public static void main(String[] args)throws Exception {
    throw new IOException("File not found");
  }/*  w  w  w .  j  a  v  a  2 s  .c  om*/