Java throw and throws Keyword Example

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;


throw new ArithmeticException();

Syntax of throws keyword

throws exceptionClassName


public void divide() throws IOException {


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.

public class CustomException extends Exception{	
	String msg;
	public CustomException(String msg)
		this.msg = msg;

import java.util.Scanner;

public class ThrowAndThrowsExample {
	int numerator;
	int denominator;
	double result;
	public void divide()throws CustomException{
		Scanner scan = new Scanner(;
		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");
		result = numerator/denominator;
		System.out.println("Result After "+numerator+"/"+denominator+" = "+result);
	public static void main(String args[])
		ThrowAndThrowsExample tt = new ThrowAndThrowsExample();
		try {
		} catch (CustomException e) {


When you will compile and execute the 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 :

Download Source Code

Share on Google+Share on Google+

Java throw and throws Keyword Example

Posted on: July 26, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Java throw and throws Keyword Example  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image