Java throws keyword

The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.

The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.

Syntax of java throws
return_type method_name() throws exception_class_name { //method code } OR throw Instance Example: throw new ArithmeticException("/ by zero");

But this exception i.e, Instance must be of type Throwable or a subclass of Throwable. For example Exception is a sub-class of Throwable and user defined exceptions typically extend Exception class. Unlike C++, data types such as int, char, floats or non-throwable classes cannot be used as exceptions.

The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on. If no matching catch is found then the default exception handler will halt the program.

class Test1 { static void fun() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside fun()."); throw e; // rethrowing the exception } } public static void main(String args[]) { try { fun(); } catch(NullPointerException e) { System.out.println("Caught in main."); } } }


Output:
Caught inside fun(). Caught in main.
Which exception should be declared

Ans) checked exception only, because:

  1. unchecked Exception: under your control so correct your code.

  2. error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword

Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.

Java throws example
import java.io.IOException; class Test1 { void m()throws IOException{ throw new IOException("device error");//checked exception } void n()throws IOException{ m(); } void p(){ try{ n(); }catch(Exception e){System.out.println("exception handled");} } public static void main(String args[]){ Test1 obj=new Test1(); obj.p(); System.out.println("normal flow..."); } }


Output:
exception handled normal flow...

Note: If you are calling a method that declares an exception, you must either caught or declare the exception.

There are two cases:
  1. Case1:You caught the exception i.e. handle the exception using try/catch.

  2. Case2:You declare the exception i.e. specifying throws with the method.

Case1: You handle the exception
  • In case you handle the exception, the code will be executed fine whether exception occurs during the program or not.
import java.io.*; class M{ void method()throws IOException{ throw new IOException("device error"); } } public class Test1 { public static void main(String args[]){ try{ M m=new M(); m.method(); }catch(Exception e){System.out.println("exception handled");} System.out.println("normal flow..."); } }


Output:
exception handled normal flow...
Case2: You declare the exception
  1. A)In case you declare the exception, if exception does not occur, the code will be executed fine.

  2. B)In case you declare the exception if exception occures, an exception will be thrown at runtime because throws does not handle the exception.

A)Program if exception does not occur
import java.io.*; class M{ void method()throws IOException{ System.out.println("device operation performed"); } } class Test1 { public static void main(String args[])throws IOException{//declare exception M m=new M(); m.method(); System.out.println("normal flow..."); } }


Output:
device operation performed normal flow...
B)Program if exception occurs
import java.io.*; class M{ void method()throws IOException{ throw new IOException("device error"); } } class Test1 { public static void main(String args[])throws IOException{//declare exception M m=new M(); m.method(); System.out.println("normal flow..."); } }


Output:
Output:Runtime Exception
Difference between throw and throws in Java

There are many differences between throw and throws keywords. A list of differences between throw and throws are given below:

No.throwthrows
1)Java throw keyword is used to explicitly throw an exception.Java throws keyword is used to declare an exception.
2)Checked exception cannot be propagated using throw only.Checked exception can be propagated with throws.
3)Throw is followed by an instance.Throws is followed by class.
4)Throw is used within the method.Throws is used with the method signature.
5)You cannot throw multiple exceptions.You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.
Java throw example
void m() { throw new ArithmeticException("sorry"); }
Java throws example
void m()throws ArithmeticException { //method code }
Java throw and throws example
void m()throws ArithmeticException { throw new ArithmeticException("sorry"); }
Que) Can we rethrow an exception?

Yes, by throwing same exception in catch block.

Important points to remember about throws keyword:
  1. throws keyword is required only for checked exception and usage of throws keyword for unchecked exception is meaningless.

  2. throws keyword is required only to convince compiler and usage of throws keyword does not prevent abnormal termination of program.

  3. By the help of throws keyword we can provide information to the caller of the method about the exception.




Instagram