Exception Handling in Java is a distinctive approach to improvise a Java application's convenience and performance capabilities. Exceptions, if not handled properly, may pose a severe threat to the application program in real-time.
Let us learn more about exceptions and how to handle them, to make sure the Java application is safe and secure.
An Exception is an unexpected event that may occur during the program's compile-time or run-time. It is capable enough to cause a severe potential threat and disrupt the entire flow of the program.
Now you might be wondering, an error does the same thing, But it is a lot more different. We will learn more about the "error" in the next section.
An exception will disturb the normal flow of any runnable program. But an error is something that contributes to making a program not capable of executing and sometimes collapse as well.
Now, an Error can be defined as follows.
An error can be defined as a state at which the computer program cannot recover, and stays in a non-executable mode or sometimes collapses from normal-execution.
To have a clear understanding of an Exception and an Error, we shall now learn the differences between them.
Error |
Exception |
Library: java.lang.Error |
Library: jav.lang.Exception |
Errors are of Unchecked type |
Exceptions are both Checked and Unchecked type |
The compiler can not understand errors |
The compiler identifies checked exceptions |
Errors are mainly encountered in the run-time |
Only the unchecked exceptions are encountered in run-time |
The program cannot recover from an error by itself |
The program can recover from exceptions as the compilers add “try and catch” blocks automatically |
The error may be caused by program logic or the run-time environment |
An exception is caused by the application |
Now that we have a clear cut differentiation and a better understanding of both, let us move ahead and learn the Exception Hierarchy in Java.
The Hierarchy of Exceptions in Java is not too complicated. All the errors and exceptions are inherited from the parent class called ‘Throwable’. Two sub-classes inherit the throwable class. One is the Error class, and the other is the Exception class.
Now, these two classes are further inherited by a few more errors and exceptions, which are shown clearly in the image below.
Now, that we have better clarity on the Exception Hierarchy, we will be briefly looking into the types of Exceptions. For a better experience, let us enter into the next section, which describes the various types of Java exceptions.
There are technically two types of Exceptions, and the third variety is an error. Those are mentioned below as follows.
The classes that inherit all the exceptions from the throwable parent class directly, but except for the run-time exception, are called the checked exceptions.
Example:
SQL Exception and IOException
//code 1:
//Checked exception (unresolved)
package Exceptions;
import java.io.*;
public class Checked {
public static void main(String[] args) {
FileReader file = new FileReader("C:\\Users\\ravi.kiran\\Documents\\data.txt");
BufferedReader Input = new BufferedReader(file);
for (int c = 0; c < 3; c++)
System.out.println(Input.readLine());
Input.close();
}
}
//code 2:
//Checked exception (resolved)
package Exceptions;
import java.io.*;
public class Checked {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("C:\\Users\\ravi.kiran\\Documents\\data.txt");
BufferedReader Input = new BufferedReader(file);
for (int c = 0; c < 5; c++)
System.out.println(Input.readLine());
Input.close();
}
}
The classes that inherit only the run-time exceptions are called as the Unchecked Exceptions.
Example:
ArithmeticException and NullPointerException
//code:
Unchecked Exceptions(Resolved)
package Exceptions;
public class Unchecked {
public static void main(String args[]) {
int Ary[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
System.out.println(Ary[11]);
}
}
An unrecoverable event that collapses the entire application program is called as an error.
Example:
OutOfMemoryError and AssertionError
With this, we have a detailed understanding of the different types of Exceptions in Java. Moving further, for a much precise clarification on the two major types of exceptions, we will learn the apparent differences between both.
The table below helps us with the differences between the Checked Exceptions and the Unchecked Exceptions.
Checked Exceptions |
Unchecked Exceptions |
Can be checked and handled during Compile-time |
Cannot be checked nor be handled during Compile-time |
Direct subclasses of exception class but do not inherit run-time exception |
Direct subclasses of exception class but only inherits run-time exception |
The compiler catches these exceptions in the compilation stage |
The compiler cannot recognize and catch them during the compilation stage |
Checked Exceptions are predictable failures |
Uncheck exceptions are unpredictable failures, mostly caused by improper programming logic |
Examples: SQL Exception IOException |
Examples: ArithmeticException NullPointerException |
So these were the evident differences between the Checked and Unchecked Exceptions in Java. Moving further, we will learn the crucial keywords necessary to carry over the exception handling process in Java.
The following are the primary keywords used in the process of Exception handling in Java.
Keyword |
Description |
try |
The “try” keyword is used to specify the exception block |
catch |
The “catch” keyword is used to specify the solution |
finally |
The “finally” keyword has a mandatorily executable code |
throw |
The “throw” keyword throws an exception |
throws |
The “throws” keyword is used to declare an exception |
With the keywords discussed, let us get into the central part of Exception Handling in Java. We will learn the methods of Exception Handling in Java.
There are two ways for Exception Handling in Java. They are as follows.
Java Virtual machine handles default exceptions. The compiler identifies the presence of an exception, it quickly packs the recognized exception in the form of an object.
The compiler sends the exception object to the JVM during the run-time. This process is called throwing an Exception.
After the exception is thrown, many methods could get executed in response to the thrown exception. The list is known as the Call Stack. The Call Stack is described as follows.
The customized/user-defined exception handling in Java is managed by using the exception handling keywords. They are:
In customized exception handling, the user should recognize/expect an exception at a specific part of the code segment.
Once the location of the exception is finalized, then, the code block should be enclosed inside the try and catch blocks.
With this setup, whenever the code throws an exception, it gets handled by the appropriate catch block.
The "throw" keyword is used to manually throw an exception. When an exception is thrown from the program, it is identified by the "throws" clause.
Now that we have clarity on the exceptions and procedures for Exception Handling in Java, we will directly deal with some of the frequently faced exceptions in Java and resolve them programmatically.
Some of the common exceptions faced in the process of Exception Handling in Java are as follows.
When you try to store a value in the array location with an address exceeding the array's maximum location value, this exception is thrown.
Example:
//ArrayIndxOutOfBound
package Exceptions;
import java.util.Arrays;
import java.util.Scanner;
public class IndexOutOfBound {
public static void main(String args[]) {
int[] Array = {(int) 10.0,(int) 20.0,(int) 30.0,(int) 40.0,(int) 50.0};
System.out.println("The array elemens are as follows: \n");
System.out.println(Arrays.toString(Array));
Scanner scan = new Scanner(System.in);
System.out.println("Please provide the address of the required element:\n");
float numbers = scan.nextFloat();
System.out.println("Number at your selected address is "+Array[(int) numbers]);
}
}
When you perform a Mathematical operation on a null value, then this exception is thrown.
Example:
//NullPointer
package Exceptions;
import java.util.Arrays;
import java.util.Scanner;
public class NullPointer {
private static String str;
public static void main(String[] args) {
str = "simplilearn";
foo(null);
bar(null);
}
static void foo(String abc) {
try {
System.out.println("First character in the string is:\n" + abc.charAt(0));
} catch (NullPointerException e) {
System.out.println("NullPointerException!");
}
}
static void bar(String abc) {
if (abc == null)
System.out.println("First character in the string is:\n " + abc.charAt(0));
else
System.out.println("NullPointerException!");
}
}
If you try to store a value with the wrong number format, like a different datatype, then this exception is thrown.
Example:
//NumberFormatted
package Exceptions;
public class NumFormat {
private static int num;
public static void main(String[] args) {
num = Integer.parseInt(null);
}
}
In case if you try to divide a number by zero, this exception is thrown.
Example:
//Divide by zero
package Exceptions;
public class DBZ {
public static void main(String args[]) {
int n1, n2;
try {
n1 = 0;
n2 = 100 / n1;
System.out.println(n2);
} catch (ArithmeticException e) {
System.out.println("The divider cannot be zero, try a differnt number.");
} catch (Exception e) {
System.out.println("You cannot execute this program: DivideByZeroException");
}
}
}
So far, we have dealt with different types of exceptions and other procedures for Exception Handling in Java. Now we will learn the best practices to be followed for Exception Handling in Java in the next section.
After we have learned the frequently faced exceptions in Java, we will now understand the best practices to be followed while implementing Exception Handling procedures in Java.
Exceptions have proven that they can be costly if used recklessly. We should use Boolean values to indicate the successful implementation of smaller operations.
It's an outstanding practice of customizing your exceptions in the design time rather than planning them on the go.
Keeping track of the exceptions comes handy as the user understands why a particular exception popped up.
An exception is expected to be thrown as early as possible and should be resolved at the same pace.
Since exceptions halt the complete program, we must ensure the system resources are shut to save the resources.
Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.
With this, we have now arrived at the end of the "Exception Handling in Java' article. We hope you enjoyed learning about the essential concepts of Interface in Java.
Exception Handling was only one of the crucial concepts for Software Development using Java.
Are you looking for more about the Java Programming Language and getting certified as a professional Java Developer? Then, check out our Java training and certification program. It is curated by the most experienced real-time industry experts.
Got a question about the "Exception Handling in Java" article? Please mention it in the comment section of this article, and we'll have our experts answer it for you right away.
Name | Date | Place | |
---|---|---|---|
Full Stack Java Developer | Cohort starts on 3rd May 2021, Weekend batch | Your City | View Details |
Full Stack Java Developer | Cohort starts on 17th May 2021, Weekend batch | Chicago | View Details |
Full Stack Java Developer | Cohort starts on 27th May 2021, Weekend batch | Houston | View Details |
Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.
Java Programming: The Complete Reference You Need
Blockchain Career Guide: A Comprehensive Playbook To Becoming A Blockchain Developer
Who Is a Full Stack Developer?
Java EE Tutorial: All You Need To Know About Java EE
10 Reasons That Explain Why You Need to Learn Java
Free eBook: Salesforce Developer Salary Report