Skip to main content

Difference Between throw and throws in Java with Examples

 

difference between throw and throws in java with examples

What is throw and throw keywords in Java? What is Difference between throw and throws?

In java, throw and throws keyword are used for Exception Declaration. throw and throws keywords are mainly used for handle the Exception. 

What is Exception and Exception handling in Java?

So let's see how both are different from each other.

1. throw

As a name suggest, throw is used to throw the Exception in java. Using throw keyword we can throw exception explicitly.

throw keyword used inside of method. It is used when it is required to throw an Exception logically. 

We can throw only one Exception at a time.

Syntax of throw :-

    throw someThrowableObject

Lets see example of throw keyword so you will get idea about it.

Example 1 :- throw exception using throw keyword

public class ExceptionDemo {

    public static void main(String[] args) {
        method();
    }
    
    public static void method() {
        System.out.println("Inside Method");
        throw new RuntimeException();
    }

}

Inside Method
Exception in thread "main" java.lang.RuntimeException
    at ExceptionDemo.method(ExceptionDemo.java:9)
    at ExceptionDemo.main(ExceptionDemo.java:4)

In above example we does not catch the exception so its throw exception trace status in output. we can also catch Exception after throw. 

Example 2 :- Handle the Exception after throw

public class ExceptionDemo {

    public static void main(String[] args) {
        try {
            method();
        } catch (Exception e) {
            System.out.println("Handled the Exception");
        }
    }
    
    public static void method() {
        System.out.println("Inside Method");
        throw new RuntimeException();
    }

}

Inside Method
Handled the Exception

2. throws 

throws keyword is used with method signature. throws keyword is used when the method has some statement that can lead to some Exception. 

we can declare multiple exception using throws keyword, separated by comma.

Syntax :-

    public void method() throws Exception {  
       // Some code
    }

Let's see example of throws keyword

Example 3 :- Declare Run time (Unchecked) exception using throws keyword

public class ExceptionDemo {

    public static void main(String[] args) {
        try {
            method();
        } catch (Exception e) {
            System.out.println("Handled the Runtime Exception");
        }
    }
    
    public static int method() throws ArithmeticException {
        int number1 = 10;
        int number2 = 0;
        return number1/number2;
    }

}

Output :-
Handled the Runtime Exception

If we throw Runtime Exception then it is not necessary to catch. It is depend on developer to handle or not.

Example 4 :- Declare Compile time (Checked) exception using throws keyword

import java.io.FileInputStream;

public class ExceptionDemo {

    public static void main(String[] args) {
       try {
            readFile();
        } catch (FileNotFoundException e) {
            System.out.println("Handled the FileNotFoundException");
        }
    }
    
    public static void readFile() throws FileNotFoundException {
        FileInputStream input = new FileInputStream("Location of file");
    }

}

If we does not use throws keyword or not handle the exception using try catch block then we get following suggestion from eclipse IDE. means we must handle Compile time Exception.

throws keyword in java with example

Let's see how we can throws multiple exception using throws keyword.

Example 5 :- throws multiple exception 

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ExceptionDemo {

    public static void main(String[] args) {
        try {
            arithmeticOperation();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Handled the Exception");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Handled the Exception");
        }
    }
    
    public static void arithmeticOperation() throws ParseException, Exception{
        String date = new Date().toString();
        SimpleDateFormat format = new SimpleDateFormat();
        format.parse(date);
    }

}

Output :-
java.text.ParseException: Unparseable date: "Mon Jan 25 21:16:42 IST 2021"
    at java.base/java.text.DateFormat.parse(DateFormat.java:395)
    at ExceptionDemo.arithmeticOperation(ExceptionDemo.java:19)
    at ExceptionDemo.main(ExceptionDemo.java:9)
Handled the Exception
 

See other articles :-


Comments

Popular posts from this blog

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...