Java throw exception

What is throws keyword in Java?

Throws keyword is used to declare that a method may throw one or some exceptions. The caller must catch the exceptions.

Suppose in your java program you using a library method which throws an Exception

you will handle this exception using try & catch.
import java.io.*; class file1{ public static void main(String[] args) { try{ FileWriter file = new FileWriter("c:\\Data1.txt"); file.write("Guru99"); file.close(); } catch(IOException){} } }

If you do not handle the exception in a try catch block, compiling will fail. But almost every other method in the java library or even user defined may throw an exception or two.

Handling all the exceptions using the try and catch block could be cumbersome and will hinder the coder's throughput.

So java provides an option, wherein whenever you are using a risky piece of code in the method definition you declare it throws an exception without implementing try catch.

The syntax of java throw keyword is given below.
throw exception; or method (Arguments) throws Exception1,Exception2,Exception,… {}
The example of throw IOException.
throw new IOException("sorry device error);
java throw keyword example

In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.

public class Test { static void validate(int age){ if(age<18) throw new ArithmeticException("not Eligiable to valid vote"); else System.out.println("Eligiable to vote"); } public static void main(String args[]) { validate(13); System.out.println("rest of the code..."); } }


Output:
not Eligiable to valid vote
Java throws Example
import java.io.*; class Test { public static void main(String[] args) throws IOException { FileWriter file = new FileWriter("c:\\Data1.txt"); file.write("cprogramcoding"); file.close(); } }


Note: To successfully the above codes, first create an empty text file with name Data1.txt in your C drive. In sum, there are two methods to handle Exceptions.

  1. Put the Exception causing code in try and catch block.

  2. Declare the method to be throwing an Exception

If either of the above two is not done, the compiler gives an error. The idea behind enforcing this rule is that you as a programmer are aware that a certain piece of code could be risky and may throw an exception.

What is the difference between throw and throws?
throw
throws
It is used to create a new Exception object and throw it It is used in method definition, to declare that a risky method is being called.
Using throw keyword you can declare only one Exception at a time Using throws keyword you can declare multiple exception at a time.

Example:

throw new IOException("can not open connection");

Example:

throws IOException, ArrayIndexBoundException;




Instagram