Introduction to Java throw exception
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. Exception Handling in Java is one of the powerful mechanisms to handle runtime errors so that the normal flow of the application can be maintained. We can use different ways to handle java exceptions. One of the ways is to use the java throw exception handling method. In this tutorial, we will learn about the java throw exception and the throws keyword to handle java exceptions.
First, we will discuss different types of java exceptions including checked and unchecked exceptions. We will also look at some of the built-in exceptions that are common and can occur frequently in the java program. At the same time, we will take various different types of java exceptions and will handle them using the throws
keyword and java throw exception method.
To summarize, this tutorial will contain all the details and necessary examples that you need to know in order to start working and handling java exceptions using the java throw exception method.
Getting started with Java throw exception
The exception refers to some unexpected or contradictory situation or an error that is unexpected. There may be some situations that occur during program development. These are the situations where the code-fragment does not work right. There are different ways to handle the exceptions. For example, using try and catch block or using java throw exception method.
You can read more about the try and catch method from the article on try catch java. In this tutorial, we will learn about java throw exceptions, but first, let us have a look at some of the built-in java exceptions and different types of exceptions. Generally, java exceptions are divided into two different types including checked, and unchecked exceptions. Let us first differentiate between these two different types.
Checked exceptions in Java
It is actually a compile-time exception that occurs when the java compiler checks or notifies during the compilation time. That is why they occur during the compile time. The compiler checks the checked exceptions during compilation to check whether the programmer has written the code to handle them or not.
We cannot simply ignore these exceptions and should handle them properly in order to run our program without any exceptions. If we will not write the code to handle them then there will be a compilation error that is why a method that throws a checked exception needs to either specify or handle it. Some of the common checked exceptions are SQLException
, ClassNotFoundException
, FileNotFoundException
, IOException
, etc.
For example, See the java program below which raise an exception because the file that we want to open does not exist.
// importing file
import java.io.File;
// importing filereader to read file
import java.io.FileReader;
// java main class
public class Main{
// java main method
public static void main(String args[]){
// creating new file typed object and opening the file
File file = new File("file.txt");
// reading file
FileReader fileReader = new FileReader(file);
}
}
Output:
Notice that we get the exception that says FileNotFoundException, which is an example of a java checked exception.
Unchecked exception in Java
Unlike checked exceptions that occur during compile time, an unchecked exception occurs during the execution of a program. It is also called a runtime exception as well. The compiler generally ignores these exceptions during compilation rather, they are checked during the runtime.
Therefore, the compiler does not check whether we have written the code to handle them or not but it is our responsibility to handle the unchecked exceptions and provide a safe exit. Some of the common unchecked exceptions in java include ArtithmeticException
, ArrayIndexOutOfBoundsException
, IllegalStateException
, NullPointerException
, etc. Now let us take an example of a java program that raises an unchecked exception.
See the java program below:
// java main class
public class Main{
// java main method
public static void main(String args[]){
// creating java array
int array[] = {1, 2, 3, 4, 5};
// printing element that doesnot exist
System.out.println(array[7]);
}
}
Output:
Notice that we get ArrayIndexOutOfBoundsExceptions
which is a type of unchecked exception.
Difference between Java throws keyword and Java throw exception
The java throw
and throws
are the concepts of exception handling where the throw
keyword throw the exception explicitly from a method or a block of code whereas the java throws
keyword is used in the method signature to declare an exception that might be thrown by the function while the execution of the code.
Internally throw
is implemented as it is allowed to throw only a single exception at a time or in simple words we cannot throw multiple exceptions with throw
keyword on another hand we can declare multiple exceptions with throws
keyword that could get thrown by the function where throws
keyword is used.
Now let us take an example and the java throw and throws
are different and help to handle exceptions. First, see the example below which use the keyword throw which is used inside the function.
// java main class
public class Main{
// java main method
public static void main(String args[]){
//calling the function
check(10);
}
// user defined function
public static void check(Integer num){
// if statement to check
if(num < 18){
// throw exception using java throw keyword
throw new ArithmeticException("You are not allowed to vote!");
}
// else statement
else {
System.out.println("You can vote!!");
}
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: You are not allowed to vote!
at Main.check(Main.java:13)
at Main.main(Main.java:6)
Notice that we had used the keyword throw
inside the user-defined function and it raises an exception when the given conditions are satisfied. Now, let us see how we can use the keyword throws
in the java program. See the example below:
// java main class
public class Main {
// java main mefhod
// java throws keyword
public static void main(String[] args)throws InterruptedException{
// thred sleeping
Thread.sleep(100);
// printing
System.out.println("Print successfully");
}
}
Output:
Print successfully
Notice that we had used the keyword throws
while defining the method which is used to handle the possible exceptions. If we will run the program without handling the exception, the program will raise an exception and will not be able to print the output.
Examples of Java throw exception
Now we are already familiar with the keyword throw
and how it is used in java programming. In this section, we will have a look at the keyword by using various examples. We will see how we can use it inside the method, for loop and inside try and catch block. See the examples below:
Example-1 Java throw an exception inside the method
We already know that the java throw keyword is used to handle an exception inside a method. Let us take an example and see how we can use it inside the java method to handle an exception. See the example below:
// java main class
public class Main {
// java main mefhod
public static void main(String[] args){
// calling java method
square(-4);
}
// user defined method
public static void square(Integer num){
// if condition
if(num<0){
// java throw exception inside method
throw new ArithmeticException("Number should not be negative!");
}
// else statement
else{
System.out.println("The square is: "+num*num);
}
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: Number should not be negative!
at Main.square(Main.java:13)
at Main.main(Main.java:6)
Notice that in the above example, we created a user-defined method that only calculates the square of positive numbers and raises an exception if negative values are given. You can read more about the calling methods with arguments and method parameters from our articles on java parameters and java arguments.
Example-2 Java throw exception inside try-catch block
Java try-catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. You can read more about the try-catch block from the article java try and catch block. Here we will see how we can use the java throw exception inside the try block. See the example below:
// java main class
public class Main {
// java main mefhod
public static void main(String[] args){
// calling java method
square(0);
}
// user defined method
public static void square(Integer num){
// try block
try{
// if statement
if (num>0){
// printing square
System.out.println("Square of the num is: " +num*num);
}
// else if statement
else if(num==0){
// java throw exception
throw new ArithmeticException();
}
}
// catch block
catch (Exception e){
System.out.println("Cannot find the square of zero!");
}
}
}
Output:
Cannot find the square of zero!
Notice that inside the try block, we are raising an exception if the number is equal to zero which will cause the catch block to execute. That is in the above example, the catch block is executed.
Example-3 Java throw exception inside for loop
The for loop in Java is an entry-controlled loop that facilitates a user to execute a block of a statement(s) iteratively for a fixed number of times. The number of iterations depends on the test condition given inside the for loop. You can read more about the for loop from the article on java for loop. Here we will see how we can raise an exception using java throw
keyword inside for loop. See the example below:
// java main class
public class Main {
// java main mefhod
public static void main(String[] args){
// for loop
for(int i=0; i<10; i++){
// if statement
if(i==5){
// java throw exception
throw new ArithmeticException("Number five is not allowed in loop!");
}
// else statement
else{
// printing the numbers
System.out.println("the number is : "+i);
}
}
}
}
Output:
the number is : 0
the number is : 1
the number is : 2
the number is : 3
the number is : 4
Exception in thread "main" java.lang.ArithmeticException: Number five is not allowed in loop!
at Main.main(Main.java:10)
Notice that the execution stops after, number 5 because we raise an exception there using the java throw
keyword.
Examples of Java throws keyword
We already had discussed the difference between java throws
and throw
keywords in our previous sections. In this section, we will take some examples and see how we can handle exceptions using the java throws
keyword. Handling all the exceptions using the try and catch block could be cumbersome and will hinder the coder’s throughput. So java provides an option, wherein whenever we are using a risky piece of code in the method definition we can declare the throws
exception without implementing try-catch. Here we will take various examples to handle java exceptions using the java throws
keyword. See the examples below.
Example-1 Single Exception and Java throws keyword
IOException is a Java exception that occurs when an IO operation fails. Here we will use keyword throws
to raise IOException if occurs. So instead of creating a new try and catch block to handle this exception, we can just use the throws
keyword to throw the possible exception that might occur. Let us take an example of an IO Exception that might occur and let see how we can use the java throws
keyword. See the example below:
// improting IO
import java.io.*;
// java main class
class Main{
// java main method
public static void main(String[] args) throws IOException{
// opening file which doesnot exist
FileWriter file = new FileWriter("Myfile.txt");
// trying to write in file
file.write("Welcome to Golinuxcloud!");
file.close();
}
}
Notice that soon after the definition of our method, we had used the keyword throws
followed by the class name of the possible exception that might occur inside our method.
Example-2 Multiple Exceptions and Java throws keyword
One of the advantages of using the throws
keyword is that we can raise multiple exceptions in just one line of code. All we need to do is to write the class names of all the exceptions that might occur in our java code after the keyword throws
. For example, see the example below:
// improting IO
import java.io.*;
// importing invalid name exception class
import javax.naming.InvalidNameException;
// java main class
class Main{
// java main method
public static void main(String[] args) throws IOException, IndexOutOfBoundsException, InvalidNameException{
// opening file which doesnot exist
FileWriter file = new FileWriter("Myfile.txt");
// trying to write in file
file.write("Welcome to Golinuxcloud!");
file.close();
}
}
Notice that we had written multiple class names of exceptions after the keyword throws
, which is fine.
Summary
Throwing an exception in Java is simple. All we need is to specify the Exception object we wish to throw. Every Exception includes a message which is a human-readable error description. In this tutorial, we learned about the java throw exception and java throws
keyword. We also covered different types of exceptions that exist in the Java programming language.
At the same time, we discussed the difference between the keyword throw
and throws
. We also covered various examples using throw and throws
keywords. Moreover, we also learned to to use multiple exception class names with throws
keyword. In a nutshell, this tutorial contains all the details and information that you need to know in order to start working with the java throw exception and java throws
keyword.
Further Reading
Java throw exception
Java exceptions
Java exception handling