This section will describe you how to throw exception/s in Java.
Java throw and throws Keyword Example
In this section we will read about how to throw the caught exception using throw and throws keywords in Java.
throws and throw keywords in Java are used in the Java Exceptions. Keyword throw throws the exception explicitly whereas the keyword throws declares the exceptions. Generally, throw keyword is used for throwing custom exceptions, instead of, this the checked or unchecked exceptions can also be thrown using this keyword. As, we said earlier throws keyword declares the exception, it indicates the line, where it is used, may occur an exception. throws keyword propagate the exception in call stack.
Syntax of throw keyword
throw keyword needs a single argument. This argument should be a Throwable object i.e. an instance of Throwable class.
throw throwableObject;
e.g.
throw new ArithmeticException();
Syntax of throws keyword
throws exceptionClassName
e.g.
public void divide() throws IOException { ..... }
Example
Here I am giving a simple example which will demonstrate you about how the throw and throws keywords can be used in the Java program. In this example we will create a simple Java class where we will use the above mentioned keywords. In this example we will create a method for dividing two numbers where an ArithmeticException may occur when the numerator will be divided by denominator.
CustomException.java
public class CustomException extends Exception{ String msg; public CustomException(String msg) { super(msg); this.msg = msg; } }
ThrowAndThrowsExample.java
import java.util.Scanner; public class ThrowAndThrowsExample { int numerator; int denominator; double result; public void divide()throws CustomException{ Scanner scan = new Scanner(System.in); System.out.println("Enter Numerator : "); numerator = scan.nextInt(); System.out.println("Enter Denominator : "); denominator = scan.nextInt(); if(denominator == 0) throw new CustomException("Denominator can't be zero"); else { result = numerator/denominator; System.out.println("Result After "+numerator+"/"+denominator+" = "+result); } } public static void main(String args[]) { ThrowAndThrowsExample tt = new ThrowAndThrowsExample(); try { tt.divide(); } catch (CustomException e) { e.printStackTrace(); //System.out.println(e); } } }
Output
When you will compile and execute the ThrowAndThrowsExample.java file then the output will be as follows :
When you will execute the above said Java file you will be prompted for giving input for the numbers, if you will give the denominator value greater than 0 (zero) then the output will be as follows :
But, when you will give the denominator value to 0 (zero) then the exception will be thrown and the output will be as follows :