×

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

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Reentrant Lock in Java

The Lock interface is implemented by the ReentrantLock class, which also provides methods for synchronising access to shared resources. The code that controls the resource has calls to the lock...

4 minutes read.

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws...

3 minutes read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

How to check Date is Greater in Java?

In this article, you will be acknowledged about how to check if the given date is greater than the other date or not. We are simply comparing the dates and...

7 minutes read.

Checked vs Unchecked Exceptions in Java

In this tutorial, we will discuss Java's checked and unchecked Exceptions. Exception An exception is an undesirable event that disrupts the normal flow of the program. An exception is thrown at runtime. It...

4 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the...

4 minutes read.

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

How to generate random numbers in Java

Random numbers, also known as fake numbers, are actually a part of a very large sequence, so they are called random numbers. In a defined set of numbers, every number...

6 minutes read.

Java Pop

The array, linked list, stack, queue, and other data structures are supported by Java programming. The insertion, deletion, and element searching operations are available for every data structure. And Java...

4 minutes read.

Java Math log10() Method

The log10() method of Math class returns the base 10 logarithmic value for the specified double argument. Syntax: public static double log10(double a) Parameters: The parameter ‘a’ represents a double value. Return Value: The log10() method...

2 minutes read.

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 minutes read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

How to download Eclipse for Java

Introduction: We write a java program, and when we want to run it, we need software to run it. Eclipse is a kind of software used to execute a JavaFX...

3 minutes read.