×

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

How to Create an Object in Java

How to Create an Object in Java An object can be defined as a run time entity that contains the blue printof the class. It means that all the member functions...

5 minutes read.

How to Convert Octal to Decimal in Java

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

2 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Access Modifier in Java

The access modifiers in java are used to change the accessibility and scope of a method, constructor, class, and fields. If you are aware of C++ language, when we declare any member...

2 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Armstrong Number Program in Java

Armstrong Number Program in Java: A positive number is called an Armstrong number if the sum of the cube of each digit is equal to the number itself. There are...

6 minutes read.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.

Automatic Resource Management

In computer programming, resource management refers to the wide set of techniques for the effective management of the system resources. There are two ways of management of resources: The computer program itself...

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

Hashtable in Java

Hashtable in Java The Hashtable class implements the Map interface and extends the Dictionary class. It implements a hash table which shows the key-value relation, i.e., it maps the keys to the values....

9 minutes read.

Default Virtual Behaviour in C++ vs Java

Virtual Behaviour in C++: The class member methods in C++ are, by default, non-virtual. This implies that by simply defining it, they can be turned into virtual. The virtual class can be...

3 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

How to Convert int to double in Java

How to Convert int to double in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

&& Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

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

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.

Program to find and replace characters on string in java

In JAVA, Strings are immutable. To overcome this Java String class contains a lot of methods to do operations on Strings. One such method is replace method. String Replace It returns a...

3 minutes read.