×

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

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax: public int compareTo(String anotherString) Parameters: anotherString: the...

2 minutes read.

Dictionary in Java

Dictionary in Java The Dictionary class represents a key-value relation which maps keys to values. In Dictionary class, every key and every value is an object. It is an abstract class associated with...

2 minutes read.

How to create a mirror image of a 2D array in Java

Problem Statement We have provided a list of m x n. here m indicates rows, and n indicates columns). Printing the fresh matrices should result in a mirror reflection of an...

2 minutes read.

Java Substring

What is a substring in Java? Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of...

4 minutes read.

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads. Concurrency The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process...

8 minutes read.

Java Math toIntExact() Method

The toIntExact() method of Java Math class returns the int value of the given long argument, throwing an exception if the value overflows an int. Syntax: public static int toIntExact (long value) Parameters: The...

2 minutes read.

Tower of Hanoi Program in Java

Tower of Hanoi Program in Java The Tower of Hanoi program in Java is written to solve a mathematical puzzle, called Tower of Hanoi, where we have three poles and n...

4 minutes read.

Java String valueOf() method

Java String valueOf() method converts different types of values into String. Such as : int to String, long to String, boolean to String, character to String, float to String, double to...

2 minutes read.

Class memory in Java

Anything specifically defined in the Java code is stored either inside the heap or the stack, which is particularly significant. Stack and heap are the two kinds of memory available...

6 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.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

How to add 6 Months to the Current Date in Java?

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

3 minutes read.

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish...

5 minutes read.

Leap Year Program in Java

Leap Year Program in Java: A leap year is a calendar year that have an extra day i.e. 366 days instead of 365 days is called leap year. In other...

2 minutes read.

Best Java Security Framework

The security of applications is currently our top concern when creating them. The applications or bits of code running over the network are exposed to dangers and may jeopardize integrity,...

3 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

Package Program in Java

Package Program in Java The package program in Java helps us to understand the significance of packages in Java. Packages are mainly used to group together similar classes, interfaces and sub-packages....

6 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.