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 last

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st