throws keyword in java

throws keyword in java is used in a method declaration, denoted which Exception can possibly be thrown by this method. By using throws keyword in java, you can place the number of exception names after throws keyword.

During the execution of the method if any exception occurred and the programmer already used throws keyword in java then execution of the current method is stopped and returned to the caller. Then it depends upon the programmer either handle this exception by catching it or can rethrow it.

throws keyword in java

throws keyword is mainly used to handle the checked exceptions. If there occurs any unchecked exception, it is the programmer’s responsibility to check before performing any operation. The throws keyword always used with a method signature.

// Exception name must be separated by  comma
type methodName(parameters) throws exceptionList
{
	// body of method
}
import java.io.IOException;

public class ExampleOfThrowsException{ 
  public static void main(String args[]){ 
   try
   { 
	   checkedExceptionByThrows(0); 
   }
   catch(Exception e)
   {
     System.out.println(e);
   } 
  }
  
  public static void checkedExceptionByThrows(int number)throws IOException, 
  ClassNotFoundException  
{
	     if(number%2 == 0)
	        throw new IOException("IOException Occurred");
	     else
	        throw new ClassNotFoundException("ClassNotFoundException Occurred");
	  } 
}

Output: java.io.IOException: IOException Occurred

Important points to remember about throws keyword:

  • throws keyword is only used for checked exception and usage of throws keyword for the unchecked exception is meaningless. If you are using throws keyword to prevent this compile-time error we can handle the exception in two ways:
    By using try-catch (As mention in above example) By using throws keyword (You can rethrow the exception)
  • By use of throws keyword you can’t prevent abnormal termination of program. I help the compiler to provide convince only.

Leave a Comment