Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Throw and Throws in Java

Last Updated on April 18, 2023 by Prepbytes

Throw and Throws in Java are two important keywords that are used for implementing the concept of Exception Handling. Here we will learn about the Throw and Throws in Java in detail. Before delving into the topic of Throw and Throws in Java, let us about Exception and Exception Handling in Brief.

What is an Exception?

An exception is an unfavorable condition that occurs while a program is running. It refers to errors that arise when there is a problem in the code being executed. For example, when a number is divided by zero ArithmeticException is thrown. In java, we can throw an exception on our own.

But why would anyone want to throw an exception on their own?

Imagine a user is asked to enter their age as input. We know that the age of a person can only be a positive number. So, if the user enters a negative or zero value as their age, we may throw an exception.

There can be more cases where the input entered by the user is considered invalid for our program. In those cases, we can manually throw an exception.

What is Exception Handling in Java?

Exception Handling in Java is one of the effective ways to handle errors that occur at run time so that the regular flow of the program can be preserved. Java Exception Handling is a process that deals with errors occurring during runtime, such as SQLException, ArrayIndexOutOfBoundsException, ClassNotFoundException, IOException, and more. It is a technique used in Java programming to detect and manage these types of errors.

What are Throw and Throws in Java?

Throw and Throws in Java would seem similar having only a difference in tenses. But, these two are very distinct from each other and are used to do different tasks. Throw and Throws in java are simple keywords used in exception handling.

What is throw in Java?

The throw keyword in java is used to throw an exception manually and logically defined by the programmer during the execution of a program, the control moves from one block to another with the assumption that the exception of the error is defined and handled accordingly.

Syntax of Throw in Java is shown below:

throw throwableObject;

A throwable object can be an instance or subclass of the Throwable class. All exceptions defined in Java are subclasses of Throwable.

Implementation of Throw in Java:
Here is a simple Java program to help understanding how to use Throw in Java.

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    void Votingage(int age){ 
            if(age<18) 
                throw new ArithmeticException("you are not eligible to vote"); 
            else 
                System.out.println("Eligible for voting"); 
    } 
   
    public static void main (String[] args)
    {
        // Implementation starts from here
        Ideone obj = new Ideone();
        obj.Votingage(16);
        System.out.println("Program Ends");
    }
}

Output:

Exception in thread "main" java.lang.ArithmeticException: you are not eligible to vote

Explanation:
In the above program, we have defined a function named “Votingage” which throws an ArithmeticException by using the “throw” keyword.

What is Throws in Java?

Throws in Java is very similar to try-catch block in working. Throws in Java are used to declare and call an exception block.

Syntax of Throws in Java is shown below:

Type method (arguments) throws Exception1, Exception2, … { }

As seen above, a method can throw multiple exceptions, which a comma should separate in the declaration. All exceptions that can be thrown by a method should be declared in the method signature using the throws keyword.

Implementing Throws in Java:
The below code will help you in understanding how to use Throws in Java.

import java.util.*;
import java.lang.*;
import java.io.*;

class TestThrows {  
    //defining division method  
    public static int divideNum(int p, int q) throws ArithmeticException {  
        int result = p / q;  
        return result;  
    }  
    //main method  
    public static void main(String[] args) {  
        TestThrows obj = new TestThrows();  
        try {  
            System.out.println(obj.divideNum(25, 0));  
        }  
        catch (ArithmeticException e){  
            System.out.println("\nNumber cannot be divided by 0");  
        }  
    }  
}

Output:

Number cannot be divided by 0

Explanation:
In the above program, we have used the throws keyword in Java to throw the error. In the main function, when we call the function “divideNum” with parameters 25 and 0. It throws error and the catch block catches the exception and we get “Number cannot be divided by 0” on the output screen.

Key Differences between Throw and Throws in Java

The table given below summarizes the main differences between Throw and Throws in Java.

                    Throw                   Throws
It uses the exception object. It uses the name of exception classes.
It can throw only one exception. It can throw multiple exceptions separated by a comma.
The syntax of throw is followed by an instance variable the syntax of throws is followed by the exception class names.
Throw is used inside the method Throws is used with the method signature.
It is used to simply throw an exception It is used for declaration of exception.
The throw could be used inside the method Throws could only be used in the method declaration.

Conclusion
In this article, we learned about the Throw and Throws in Java and how they are used to throw the Exceptions in a Java Program. We have also discussed the differences between Throw and Throws in Java. Hope you have understand the concept of Throw and Throws in Java well.

Frequently Asked Questions (FAQs)

Here are some Frequently Asked Questions related to “Throw and Throws in Java”.

Ques 1. What is the main difference between throw and throws in Java?
Ans. ‘throw’ is a keyword in Java used to explicitly throw an exception in the program, while ‘throws’ is a keyword used in the method definition to indicate that the method may throw an exception.

Ques 2. Can we use throw without catch in Java?
Ans. Yes, we can use the ‘throw’ keyword without a ‘catch’ block in Java.

Ques 3. What happens if an exception is not caught in Java?
Ans. If an exception is not caught in Java, the program terminates abruptly and displays an error message with the stack trace.

Ques 4. How can we create a custom exception in Java?
Ans. To create a custom exception in Java, we need to create a new class that extends the Exception class or any of its subclasses.

Ques 5. Can we throw multiple exceptions in a single method in Java?
Ans. Yes, we can throw multiple exceptions in a single method using the throw and throws in Java. We can use the ‘throw’ keyword to throw multiple exceptions, and we can also use the ‘throws’ keyword to declare that a method can throw multiple exceptions.

Leave a Reply

Your email address will not be published. Required fields are marked *