×

Java throw

Java throw

Sometimes it is required in the code to throw an exception deliberately. In order to achieve the same, the Java throw keyword should be used. One can throw either unchecked or checked exceptions using the throw keyword.  However, the throw keyword is mainly used to generate custom exceptions with the help of the throws keyword.

Syntax:

throw exception;

For example:

throw new IOException(“The device is not found.”);

Java throw Keyword

Let’s try to understand the usage of the keyword throw with the help of some examples.

Throwing an Unchecked Exception

FileName: ThrowExample.java

 public class ThrowExample
{
  // A method that throws an exception   
  public void divideByZero()
  {
    // throwing the exception intentionally  
    throw new ArithmeticException("0 is used as a divisor in the division process.");
  }
  // main method
  public static void main(String argvs[])
  {
     // creating an object of the ThrowExample class 
    ThrowExample obj = new ThrowExample();
    try
    {
        // invoking the method divideByZero
        obj.divideByZero();
    }
    // handling the exception
    catch(Exception te)
    {
        System.out.println(te);
    }
  }
} 

Output:

java.lang.ArithmeticException: 0 is used as a divisor in the division process.

Explanation: The try-catch block handles the explicitly raised exception in the divideByZero() method. Note that ArithmeticException is an example of an unchecked exception.

Throwing a Checked Exception

FileName: ThrowExample1.java

 // importing the exception IOException
import java.io.IOException;
public class ThrowExample1
{
// main method
public static void main(String argvs[])
{
// handling the exception
try
{
  throw new IOException("Unable to find the file.");
}
catch (IOException IOExObj)
{
  System.out.println(IOExObj.getMessage());
}
System.out.println("Remaining code that follows the try - catch block.");
}
} 

Output:

Unable to find the file.
Remaining code that follows the try - catch block.

Explanation: Now, the throw keyword generates a checked exception that is being handled in the try-catch block. Note that the IOException is a checked exception.

Throwing a Custom Exception

The Java throw keyword can also be used to throw a custom exception. Custom exceptions play a very important role in Java projects. It is seen that most of the time, custom exceptions are used more frequently as compared to inbuilt exceptions. Custom exceptions come in very handy to show the project-specific messages. The following illustrates how one can raise a custom exception.

FileName: ThrowExample2.java

 class InvalidNumberException extends Exception
{ 
// constructor of the class
InvalidNumberException(String str)
{
// invoking the constructor of the parent class
super(str); 
}
} 
public class ThrowExample2
{ 
// main method
public static void main(String argvs[])
{
  try
  { 
    // custome exception is raised
    throw new InvalidNumberException("25 is not valid number. Number should be less than 20.");
  }
  // handling the raised custom exception
  catch(Exception e)
  {
      System.out.println("An exception occurred: "+ e);
  } 
  System.out.println("Code following the try catch block."); 
} 
}  

Output:

 An exception occurreda: InvalidNumberException: 25 is not valid number. Number should be less than 20.
Code following the try catch block. 

Explanation: Exception class must be used as a parent class to create our own exception. In order to show the desired messages, the constructor of the parent class, i.e., Exception class, must be invoked. The super(str); statement is doing the same. The rest of the code is straightforward to understand.


Related Topics

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable...

4 minutes read.

Java Worker Class

What is a Worker? A service which executes Work - flow and Activities is referred to as a Worker. On user-controlled hosts, workers are defined and put into action. The Worker...

3 minutes read.

Java Default Keyword

The Default keyword in java programming language is used as access modifier.If any of the variable or the constructor or the methods or the classes are not assigned with the...

3 minutes read.

Java String equals() method

equals() method compares two string based on the their content. Syntax public boolean equals(Objects anObject) parameter anObject: Object to be compared with the current String. Returns It returns true when the current String is equivalent to...

1 minute read.

How to Convert Decimal to Binary in Java

How to Convert Decimal to Binary in Java There are two methods to convert Decimal to Binary. Using toBinaryString() method Using user-defined logic Using Integer.toBinaryString() The toBinaryString() is a static method of Integer...

2 minutes read.

Three Partition Problems in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

8 minutes read.

Object class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM mostly generally...

6 minutes read.

Java URL Class with Example

Java URL Uniform Resource Locator To find any resource on the internet, you need to have an address of it. The URL and IP addresses are the pointers used for this purpose....

12 minutes read.

Java Location

PATH is an environmental variable that the system software now uses to find executable files (.exe) or Java binaries ( java or javac command). Once chosen, a route cannot be...

3 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Diamond problem in Java

The Diamond Problem in Java is connected to multiple inheritances. It is also referred to as the "deadly diamond dilemma" or even the "deadly diamond of death”. The solution for...

5 minutes read.

Java Class Keyword

We know that java is object-oriented programming language which contains the essential key concepts such as classes and objects etc to have clear idea about the object-oriented programming.Java is mainly...

3 minutes read.

Java Read File

Java provides its users with many ways of reading a file. To read a text file, you can use a FileReader, BufferedReader, or Scanner. Each utility offers something special for...

6 minutes read.

Java 13 New Features

The Java SE Platform's JDK 13 version is an open-source reference implementation defined by the Java Community's JSR 388 Process. The necessary modifications made in Java 13 are listed below....

6 minutes read.

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.

How to Read XML Files in Java?

Introduction Today, we are going to learn about how to read XML files in java. Before, reading the XML Files let us learn about XML. XML Files The full form of XML is...

8 minutes read.

How to open the Java control panel

The many methods for launching the Java control panel will be covered in this section. We will also go through how the Java Control Panel can be used. Java Control Panel The...

2 minutes read.

Java Clone Array

We frequently need to copy an array to back up its original components. We have a few unique numbers and strings, including Armstrong numbers, palindrome numbers, and palindrome strings. To...

4 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

How to Create an Immutable Class in Java

How to Create an Immutable Class in Java In Java, immutable means something that cannot be change. A class is called an immutable class if its content cannot be changed, once...

3 minutes read.