Java - Throwing an Exception

Introduction

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

Syntax

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");

Demo

import java.io.IOException;

public class Main {

  public static void main(String[] args)throws Exception {
    throw new IOException("File not found");
  }//from ww w  .  j a  va 2  s. c  o m
}

Result