Introduction
Exceptions date back to the dawn of programming. Exceptions were used to change the flow of the program and avoid hardware failures back when programming was done via low-level programming languages. Today, many modern languages, such as Java, Python and Ruby, provide powerful exception handling mechanisms. This feature makes a programming language robust.
This article includes several examples demonstrating how to use the “throw” and “throws” keywords in the exception-handling process.
Using throw and throws
Any code, either general or from a package written by someone else, such as the packages included with the Java platform and the Java runtime environment, can throw an exception. The throw keyword is always used to throw the exception, regardless of what causes it.
Similarly, the keyword throws is used to declare exceptions that may occur in the program. Methods that can throw exceptions must use throws to list the anticipated exceptions.
As you may have seen, the Java platform has a significant number of exception classes. All the classes are derived from Throwable, and they all allow programs to distinguish between the various forms of exceptions that can occur during program execution.
The throw keyword
Good exception handling is essential for keeping our application running after the appearance of those undesirable moments.
To throw an exception explicitly from the code, we use the throw keyword.
A single argument is required for the throw statement: a throwable object. This object is an instance of any subclass of the Throwable class.
For Example: Let's take a closer look at the throw statement. The pop method in the following code comes from a class that implements an ordinary stack object. The method returns the object after removing the top element from the stack.
public Object pop()
{
Object obj;
if (size == 0)
{
throw new EmptyStackException();
}
obj = objectAt(size - 1);
setObjectAt(size - 1, null);
size--;
return obj;
}
- The pop method examines the stack to see if any elements are present. Pop creates a new EmptyStackException object and throws it if the stack is empty.
- The declaration of the pop method does not include a throws clause. Because EmptyStackException is a RuntimeException and its subclasses are unchecked exceptions.
- It is not mandatory to handle an unchecked exception or declare it in the throws clause inside a method or constructor.
Case 1: How to throw a built-in exception using the throw keyword
To throw an exception that is already defined in the Java library, we simply use the throw keyword. If the first number is zero, the program throws an ArithmeticException with the throw keyword in the example below.
import java.io.IOException;
public class TestThrow
{
static int sum(int num1, int num2)
{
if (num1 == 0)
throw new ArithmeticException("First parameter is zero!!");
else
System.out.println("Addition is possible!!");
return num1+num2;
}
public static void main(String args[])
{
int ans = sum(0,12);
System.out.println(ans);
}
}
Output
Case 2: How to throw a custom exception using the throw keyword
To throw an exception that isn't defined in the Java library, we must create a custom exception class to define the exception that we want to throw.
In the example below, if the age is less than 18, the program throws an instance of the custom exception class using the throw keyword. Also, notice that we have used the throw and throws keyword simultaneously in this program.
class CustomException extends Exception
{
CustomException(String s)
{
super(s);
}
}
public class ChainedExceptionTest
{
static void validate(int age)throws CustomException
{
if(age<18)
throw new CustomException("Invalid Age");
else
System.out.println("Successful!!");
}
public static void main(String args[])
{
try
{
validate(13);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
Output
Also see, Swap Function in Java
The throws keyword:
In Java programming, the throws keyword is used to declare an exception in the program. It notifies the programmer that an exception may occur. Hence the programmer should provide exception handling code to maintain the regular flow in the program execution.
Syntax:
<returntype> methodname() throws ExceptionClassName{...}
Example: Here’s a program which demonstrates how the throws keyword can propagate checked exceptions.
import java.io.IOException;
public class TestThrows
{
void method1()throws IOException
{
throw new IOException("System Error!!");//checked exception
}
void method2()throws IOException
{
method1();
}
void method3()
{
try
{
method2();
}
catch(Exception e)
{
System.out.println("Exception handled in catch block!!");
}
}
public static void main(String args[])
{
TestThrows obj=new TestThrows();
obj.method3();
System.out.println("The Normal flow continued!!");
}
}
Output
Case 1: Handling the exception using try-catch block
If you handle the exception using try-catch, the code will run smoothly irrespective of whether the exception occurs during the run or not.
Program:
import java.io.*;
class Test
{
void method()throws IOException
{
throw new IOException("System error!!");
}
}
public class TestThrows
{
public static void main(String args[])throws IOException
{
try
{
Test m=new Test();
m.method();
}
catch(Exception e)
{
System.out.println("Exception handled in catch block!!");
}
System.out.println("The Normal flow...");
}
}
Output
Case 2: Declaring the exception using throws
If you declare an exception, the code will normally execute if the exception does not occur. An exception will be thrown at runtime if an exception occurs because throws do not handle exceptions.
Program when an exception occurs:
import java.io.*;
class Test
{
void method()throws IOException
{
throw new IOException("System error!!");
}
}
public class TestThrows
{
public static void main(String args[])throws IOException
{
//declare exception
Test m=new Test();
m.method();
System.out.println("The Normal flow...");
}
}
Output
Program when an exception does not occur:
import java.io.*;
class Test
{
void method()throws IOException
{
System.out.println("Device operation performed!!");
}
}
public class TestThrows
{
public static void main(String args[])throws IOException
{
//declare exception
Test m=new Test();
m.method();
System.out.println("The Normal flow...");
}
}
Output
Also read, Duck Number in Java and Hashcode Method in Java