Home Java How to Throw Exception in Java

How to Throw Exception in Java

The throw keyword in Java is used to throw an exception explicitly. The exception object that is thrown is specified. The Exception has a message attached to it that describes the error. These errors could be caused entirely by user inputs, the server, or something else.

In Java, the throw keyword is used to throw an exception from a method or any other piece of code. Throwing custom exceptions is the most common use of the throw keyword. We have the option of throwing a checked or unchecked exception.

If we divide a number by another number, we can throw an ArithmeticException. First, we must set the condition and use the throw keyword to throw an exception. We may also use the throw keyword to establish our circumstances and explicitly throw exceptions.

Java Throw

The syntax is as follows:

throw Instance

Example:

throw new ArithmeticException("/ by zero");

However, Instance must be of type Throwable or a subclass of Throwable in this case. This is because user-defined exceptions often extend the Exception class, a Throwable subclass. Unlike C++, data types like int, char, float, and non-throwable classes cannot be utilized as exceptions.

The program’s flow of execution halts immediately after the throw statement is run. The nearest enclosing try block is examined for a catch statement that fits the exception type. If a match is found, control is passed to that statement. Otherwise, the next enclosing try block is examined, and so on. The default exception handler will terminate the application if no matching catch is found.

// program  demonstrating the use of throw
class ThrowExcep
{
	static void play()
	{
		try
		{
			throw new NullPointerException("trial");
		}
		catch(NullPointerException e)
		{
			System.out.println("Caught inside play().");
			throw e; // rethrowing the exception
		}
	}

	public static void main(String args[])
	{
		try
		{
			play();
		}
		catch(NullPointerException e)
		{
			System.out.println("Caught in the main method");
		}
	}
}

}

Example: throw

// program demonstrating how to use throw
class throwTest
{
	public static void main(String[] args)
	{
		System.out.println(1/0);
	}
}

throws

In Java, the term throws is used in the method signature to indicate that the method may throw one of the given type exceptions. Therefore, the caller of these methods must use a try-catch block to handle the exception.

The syntax is as follows:

type method_name(parameters) throws exception_list

An exception list is a comma-separated list of all possible exceptions thrown by a method. If there’s a chance of raising an exception in a program, the compiler will always warn us about it, and we must handle that checked exception. Otherwise, we’ll get a compile-time warning that says unreported exception XXX must be caught or declared to be thrown. We can handle the exception in two ways to avoid this compile-time error:

  • Using the try-catch method
  • Using the throws keyword

We can use the throws keyword to delegate exception handling to the caller (which could be a method or a JVM), and then the caller method is responsible for handling the exception.

// program illustrating the error in case
// of unhandled exception
class testError
{
	public static void main(String[] args)
	{
		Thread.sleep(10000);
		System.out.println("Codeunderscored");
	}
}

In the prior application, we are obtaining a compilation time error because if the main thread goes to sleep, other threads will have the opportunity to execute the main() method, resulting in an InterruptedException.

// program illustrating how throws functions
class testError
{
	public static void main(String[] args)throws InterruptedException
	{
		Thread.sleep(10000);
		System.out.println("Codeunderscored");
	}
}

We handled the InterruptedException in the following program using the throws keyword, and the output is Codeunderscored.

Example: demonstrating how throws works

class demoThrowsExecp
{
	static void play() throws IllegalAccessException
	{
		System.out.println("Inside play(). ");
		throw new IllegalAccessException("demonstrating Throws exception");
	}
	public static void main(String args[])
	{
		try
		{
			play();
		}
		catch(IllegalAccessException e)
		{
			System.out.println("caught in main method.");
		}
	}
}

Essential things to keep in mind while using the keyword “throws”:

  • The throws keyword is only required for checked exceptions; it is pointless to use it for unchecked exceptions.
  • The throws keyword is just required to persuade the compiler; it does not prevent abnormal program termination.
  • We can offer details about the exception to the method’s caller using the throws keyword.

Example : How to Throw Unchecked Exception

public class testThrowUncheckedException {

public class testThrowUncheckedException {   

    //function to check if person is eligible to vote or not   
    public static void validate(int score) {  
        if(score<70) {  
            //throw Arithmetic exception if not eligible to vote  
            throw new ArithmeticException("Student cannot qualify for this course");    
        }  
        else {  
            System.out.println("Student qualifies to take this course!!");  
        }  
    }  
    //main method  
    public static void main(String args[]){  
        //trigger the function  
        validate(65);  
        System.out.println(" After primary code execution");    
  }    
}    

An unchecked exception is thrown by the code above. We can also throw unchecked and user-defined exceptions in the same way. If a method throws an unchecked exception, it must be handled or declared in the throws clause. If we use the throw keyword to throw a checked exception, we must handle it with a catch block or declare it with a throws declaration in the method.

Example: How to Throw Checked Exceptions

import java.io.*;  
  
public class TestThrowCheckedException {   
  
    //function to check if a student qualifies for a specified course or not   
    public static void method() throws FileNotFoundException {  
  
        FileReader file = new FileReader("C:\\Users\\Code\\Desktop\\underscored.txt");  
        BufferedReader fileInput = new BufferedReader(file);  
  
      
        throw new FileNotFoundException();  
      
    }  
    //main method  
    public static void main(String args[]){  
        try  
        {  
            method();  
        }   
        catch (FileNotFoundException e)   
        {  
            e.printStackTrace();  
        }  
        System.out.println(" runs after the rest of the code");    
  }    
}    

In Java, every Error and RuntimeException subclass is an unchecked exception. Everything else in the Throwable class is a checked exception.

Example: How to Throw User-defined Exceptions

// class representation of user-defined exceptions
class classUserDefinedException extends Exception  
{  
    public classUserDefinedException(String strVal)  
    {  
        // Calling constructor of parent Exception  
        super(strVal);  
    }  
}  
// Class using the above UserDefinedException  
public class TestThrowUserDefinedException
{  
    public static void main(String args[])  
    {  
        try  
        {  
            // throw an object of user defined exception  
            throw new classUserDefinedException("Elucidating user-defined exceptions");  
        }  
        catch ( classUserDefinedException userdefExceptions)  
        {  
            System.out.println(" Exceptions caught ");  

            // Printing UserDefinedException's message object  
            System.out.println(userdefExceptions .getMessage());  
        }  
    }  
}   

Conclusion

Exceptions in Java allow us to produce high-quality code by checking problems at compile time rather than runtime. We may build custom exceptions to make code recovery and debugging easier.

You may also like

Leave a Comment