Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Exception in Java
3.
Throw Keyword
4.
Throwing Unchecked Exception
4.1.
Example
4.2.
Output
4.3.
Explanation
5.
Throwing Checked Exception
5.1.
Example
5.2.
Output
5.3.
Explanation
6.
Throwing User-Defined Exception
6.1.
Example
6.2.
Output
6.3.
Explanation
7.
FAQs
8.
Key Takeaways
Last Updated: Mar 27, 2024

Throw in Java

Author Saksham Gupta
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

When it comes to technical interviews, interviewers frequently focus on exceptions. The questions are mostly theoretical, and one's understanding of exceptions should be on point. On the other hand, you do not need to be concerned about any of it. Ninjas are here to help, and today we'll go over one of the most often asked topics about this subject., i.e., Throw keyword in Java.

Recommended Topic, Multithreading in javaDuck Number in Java

Exception in Java

Before coming to throw keyword, we should understand what does exception in java means? 

Exceptions in Java allow us to produce high-quality code where errors are verified at compile time rather at runtime, and we may build custom exceptions to make code recovery and debugging easier.

Source: source

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Throw Keyword

The throw keyword in Java is used to explicitly throw an exception. We define the exception object that will be thrown. The Exception is accompanied by a message that describes the error. These exceptions could be due to user inputs, the server, or something else.

The throw keyword in Java allows us to throw either checked or unchecked exceptions. Its primary use is to throw a custom exception. 

We may also construct our own set of circumstances and explicitly throw an exception by using the throw keyword. For example, if we divide one number by another, we can throw an ArithmeticException. We only need to establish the condition and throw the exception using the throw keyword here.

The throw keyword in Java is used to explicitly throw an exception. We define the exception object that will be thrown. The Exception is accompanied by a message that describes the error. These exceptions could be due to user inputs, the server, or something else.

The throw keyword in Java allows us to throw either checked or unchecked exceptions. Its primary use is to throw a custom exception. 

We may also construct our own set of circumstances and explicitly throw an exception by using the throw keyword. For example, if we divide one number by another, we can throw an ArithmeticException. We only need to establish the condition and throw the Exception using the throw keyword here.

But how?

Let's see the syntax of the throw keyword.

throw new exception_class("error message");  


Now, there are a total of three kinds of exceptions you can throw. Let's give a look at all three. Try it on online java compiler.

Throwing Unchecked Exception

If a program throws an unchecked exception, it indicates that there is an issue in the program logic.

For example, dividing a number by 0 will result in an ArithmeticException. Let's look at an example of the same.

Example

class Test {  
   
    /* This function will check */
    public static void Checker(int num) {  
        if(num<18) {  
           
            /* ArithmeticException would be thrown */  
            throw new ArithmeticException("Ineligible");    
        }  
        else {  
            System.out.println("Eligible");  
        }  
    }  
 
    public static void main(String args[]){
       
        /* Checking */
        Checker(13);      
  }    
}

Output

Exception in thread "main" java.lang.ArithmeticException: Ineligible
at Test.Checker(Main.java:8)
at Test.main(Main.java:18)

Explanation

We can see that Exception is caught, and we get output as 'Ineligible,' and then we get the error message.
 

Also see,  Swap Function in Java

Throwing Checked Exception

Checked exceptions, in general, represent errors that are beyond the program's control. If the input file does not exist, the constructor of FileInputStream throws a FileNotFoundException. Java verifies checked exceptions throughout the compilation process. As a result, we need to define a checked exception with the throws keyword. Let's look at an example of the same.

Example

import java.io.*;  
class Test {  
 
    /* Exception for File Not Found */
    public static void method() throws FileNotFoundException {  
 
        /* Reading the file */
        FileReader f = new FileReader("C:\\Users\\Saksham\\Desktop\\Test.txt");  
        BufferedReader fI = new BufferedReader(f);  
       
        /* Exception thrown */
        throw new FileNotFoundException();  
    }  
   
    public static void main(String args[]){
       
        /* Try and Catch */
        try  
        {  
            method();  
        }  
        catch (FileNotFoundException eM)  
        {  
            eM.printStackTrace();  
        }  
       
  }    
}

Output

java.io.FileNotFoundException: C:\Users\Saksham\Desktop\Test.txt (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at Test.method(Main.java:8)
at Test.main(Main.java:20)

Explanation

This will throw an exception as no file will be found.

Throwing User-Defined Exception

Java allows us to construct our own exceptions, which are essentially derived classes of Exception. A custom exception, also known as a user-defined exception, is created when we create our own Exception.  Let's look at an example of the same.

Example

class UserDefined extends Exception  
{  
    public UserDefined(String str)  
    {  
        /* Calling constructor of parent Exception */  
        super(str);  
    }  
}  
/* Used for Exception */  
class TestingClass  
{  
    public static void main(String args[])  
    {  
        try  
        {  
            /* This is used to throw an exception */
            throw new UserDefined("User Defined Exception");  
        }  
        catch (UserDefined obj)  
        {  
            System.out.println("Exception Caught");  
            System.out.println(obj.getMessage());  
        }  
    }  
}  

Output

Exception Caught
User Defined Exception

Explanation

You can see that we have created user-defined exception.

Must Read Type Conversion in Java

FAQs

  1. Why is Java a platform-independent language?
    Because it does not rely on a platform, Java is platform-independent. Java will now be a platform-agnostic language. Programs are compiled into byte code in Java, which is platform-agnostic. The Java Virtual System is required to run byte code on any machine.
     
  2. Why is Java not a purely object-oriented language?
    Because it supports primitive data types such as int, byte, long, short, and so on, Java is not a fully object-oriented language. As a result, data types such as int, float, double, and others are not object-oriented. As a result, Java is not entirely object-oriented.
     
  3. What is the use of the Java util package?
    It contains the classes needed to make an applet that can communicate with its applet context. It includes all of the classes needed to create user interfaces as well as paint graphics and pictures.
     
  4. Why do we use import Java util.*?
    It means importing all the classes and interfaces within java.util package and making them available within the current class or interface. This is shorthand wild card annotation for importing all classes within a particular package.
     
  5. Is there any other Data Structures and Algorithms content in Coding Ninjas Studio?
    It entails bringing all of the classes and interfaces in the java.util package into the current class or interface. This shortcut wildcard annotation is for importing all classes included within a specific package.

Key Takeaways

In this article, we have extensively discussed Throw in JavaWe hope that this blog has helped you enhance your knowledge of Throw in Java, and if you would like to learn more, check out our articles on Library. Do upvote our blog to help other ninjas grow. Happy Coding!”

Recommended Readings:

Why is Java Platform Independent 

Hashcode Method in Java

Super Keyword In Java

Multithreading in Python

Previous article
ClassNotFoundException in Java
Next article
Throw keyword
Live masterclass