throws keyword in java

In java throws keyword is used to declare an exception.

throws keyword is also used in java to overcome the problem of exception propagation which was not possible using throw keyword with context to checked exceptions such as IOException, SQLException, etc. which we have already seen in previous topic of Exception Propagation.

throws keyword gives the programmer an information that there may occur an exception, so it is better to sort out the problem using exception handling to maintain the normal flow of execution of the program.

Syntax of throws keyword

return_type method_name() throws Exception_class_name { statement 1; statement 2; }

Checked exception can be propagated into the calling chain of the stack call.

Let’s see a java program to show use of propagation of checked exception

import java.io.IOException;
class ExceptionDemo1 { void a() throws IOException { throw new IOException("File Error"); } void b() throws IOException { a(); } void c() throws IOException { b(); }
public static void main(String args[]) throws IOException { ExceptionDemo1 obj=new ExceptionDemo1(); try { obj.c(); }catch(Exception e){ } System.out.println("Normal flow..........."); } }

Output:

Explanation:

In the above program, the method a ( ) is declared with the IOException, then it must be caught or declared to be thrown. It means, if method a ( ) is not handled by the calling method b ( ), then method b ( ) has to also declare the IOException and so on. That’s why in the above program the IOException is being handled in the main function, therefore main ( ) also has to declares the IOException i.e.