Throwing an exception in Java - Java tutorial

Throwing An Exception

You can throw an exception explicitly using the throw statement.

For e.g.

You need to throw an exception when a user enters a wrong login ID or password.

The throws clause is used to list the types of exception that can be thrown during the execution of a method in a program.

Using the throw Statement

  1. The throw statement causes termination of the normal flow of control of the java code and stops the execution of the subsequent statements.
  2. The throw clause transfers the control to the nearest catch block handling the type of exception object throws.
  3. If no such catch block exists, the program terminates.

The throw statement accepts a single argument, which is an object of the Exception class

Syntax to declare the throw statement,

throw ThrowableObj

You can use the following code to throw the IllegalStateException exception:

class ThrowStatement

{

Static void throwdemo ( )

{

try

{

throw new IllegalStateException ( );

}

catch (NullPointerException objA)

{

System.out.println (“Not Caught by the catch block inside throwDemo ().”);

}

}

public static void main (String args[ ])

{

try

{

throwDemo ( );

}

Catch (IllegalStateException objB)

{

System.out.println (“Exception Caught in:”+objB);

}

}

}

Output

javac ThrowStatement.java

java ThrowStatement

Exception Caught in: java.lang.IllegalStateException

Using the throws Statement

The throws statement is used by a method to specify the types of exceptions the method throws. If a method is capable of raising an exception that it does not handle, the method must specify that the exception have to be handled by the calling method.

This is done using the throws statement. The throws clause lists the types of exceptions that a method might throw.

Syntax to declare a method that specifies a throws clause,

[< access specifier >] [< modifier >] < return type > < method name > [< arg list >] [ throws <exception list >]

For e.g.

You can use the following code to use the throws statement:

class ThrowsClass

{

static void throwMethod ( ) throws ClassNotFoundException

{

System.out.println (“ In throwMethod “);

throw new ClassNotFoundException ( );

}

public static void main (String args [ ])

{

try

{

throwMethod ( );

}

catch ( ClassNotFoundException ObjA)

{

System.out.println (“ throwMethod has thrown an Exception :” +ObjA);

}

}

}

Output

javac ThrowsClass.java

java ThrowsClass

In throwMethod

throwMethod has thrown an Exception : java.lang.ClassNotFoundException

Recent content