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

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And ...

Sales by Match HackerRank Solution | Java Solution

HackerRank Sales by Match problem solution in Java   Problem Description : Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n=7 socks with colors socks = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .   Example 1 : Input : n = 6 arr = [1, 2, 3, 4, 5, 6] Output : 0 Explanation : We have 6 socks with all different colors, So print 0. Example 2 : Input : n = 10 arr = [1, 2, 3, 4, 1, 4, 2, 7, 9, 9] Output : 4 Explanation : We have 10 socks. There is pair of color 1, 2, 4 and 9, So print 4. This problem easily solved by HashMap . Store all pair of socks one by one in Map and check if any pair is present in Map or not. If pair is present then increment ans variable by 1 ...