Java Tutorial : Throwing An Exception – Part 1
You can throw an exception explicitly using the throw statement. For example, you need to throw an exception when a user enters a wrong loginID or password. The throws clause is used to list the types of exceptions that can be thrown during the execution of a method in a program.
Using the throw Statement
The throw statement causes termination of the normal flow of control of the Java code and stops the execution of the subsequent statements if an exception is thrown when the throw statement is executed. The throw clause transfers the control to the nearest catch block handling the type of exception object throws. If no such catch block exists, the program terminates. The throw statement accepts a single argument, which is an object of the Exception class.
The following syntax shows how to declare the throw statement:
throw ThrowableObj
In the preceding syntax, ThrowableObj is an object of the Throwable class or a subclass of the Throwable class, such as Exception class. The ThrowableObj object is created using the new operator. The Java compiler gives an error if the ThrowableObj object does not belong to a valid Exception class. You can use the following code to throw the IllegalStateException exception:
class ThrowStatement
{
static void throwDemo()
{
try
{
throw new IllegalStateException();
// creating and throwing an object of the
IllegalStateException class.
}
catch(NullPointerException objA)
{
System.out.println(“Not caught by catch block inside
throwDemo().”);
}
}
public static void main(String args[])
{
try
{
throwDemo();
}
catch(IllegalStateException objB)
{
// catching an object of the
IllegalStateException class.
System.out.println(” Exception Caught in :” + objB);
}
}
}
In the preceding code, the new operator is used to construct an object of IllegalStateException. In the throwDemo() method , an exception of the type IllegalStateException is thrown.
The output of the preceding code is:
Displaying the Description of an Exception
The built-in exception classes in Java have two types of constructors: one with no parameter and another with a String parameter that defines the exception. The String parameter that you pass to the constructor of an exception can be displayed when exception object is passed as an argument to the System.out.println() statement. The following code shows the use of constructor of the IlegalStateException with String parameter:
class ThrowClass
{
static void throwDemo()
{
try
{
throw new IllegalStateException(“MyException”);
}
catch(IllegalStateException objA)
{
System.out.println(“Caught:” + objA);
}
} // End of throwDemo() method.
public static void main(String args[])
{
throwDemo();
}
}// End of the ThrowClass.
In the preceding code, description added to the constructor of the IllegalStateException exception is displayed as MyException.
The output of the preceding code is:




View Comments
Trackbacks
Leave a Reply