throw and throws keyword in Java

throw keyword in Java

  • The throw statement is used to throw an exception.
  • You can throw an instance of checked, unchecked or error using throw keyword.

Syntax of throw keyword-

throw ExceptionClassObject;

Example

throw new FileNotFoundException("File is not present");

throws keyword in Java

  • The throws statement is used in the method declaration to inform that this method may throw the specified exception.
  • A method can specify more than one comma-separated class names of exceptions in the throws clause.
  • A method can throw runtime exceptions or errors without declaring them in the throws clause.
  • A method can throw checked exceptions which are of the same class or derived class, mentioned in the throws clause.
    void aMethod() throws FileNotFoundException{
    	//code
    	throw new ClassNotFoundException();
    }

    The above code will give compile time error as ClassNotFoundException is not a subclass of FileNotFoundException.

How to deal with method that throws an exception

When a method declares to throw an exception, in that case, you can do any one of the followings-

  1. You handle the exception using try-catch block
  2. You declare the exception using throws clause.

Case 1: Handle the exception

import java.io.*;
class Test
{
	public static void show() throws FileNotFoundException
	{
		throw new FileNotFoundException("File does not exist");
	}
	public static void main(String args[])
	{
		try
		{
			show();
		}
		catch(FileNotFoundException e)
		{
			System.out.println("Exception is handled");
		}
		System.out.println("Normal flow");
	}
}

Output

Exception is handled
Normal flow

Case 2: Declare the exception

import java.io.*;
class Test
{
	public static void show() throws FileNotFoundException
	{
		throw new FileNotFoundException("File does not exist");
	}
	public static void main(String args[]) throws FileNotFoundException
	{		
		show();		
		System.out.println("Normal flow");
	}
}

Output

Runtime Exception