Java is one of the most popular programming languages in the world. Apart from it being an OOP (Object Oriented Programming) language, another reason for the success of Java is its exception handling capacity. No matter how perfectly we write a program, there are always some exceptions that can occur in the code. How well we handle these exceptions is what makes our program robust. Thankfully exception handling in Java is very easy to learn and use. Today we will discuss exception handling in Java with examples.
Exceptions in Java are abnormal conditions that disturb the normal flow of the program. They occur during the runtime of a program. Whenever any unwanted condition arises that causes the program to execute inappropriately or stops its execution, it is an exception.
Due to its nature, there are chances that exceptions are misunderstood with errors. However, there is a huge difference between errors and exceptions. Errors, on the one hand, indicate a condition that cannot be handled during the runtime. Exception handling in Java, on the other hand, is a condition that can be and should be handled by an application during the runtime.
There are several reasons that can cause an exception in a program. For instance, if you try to open a non-existing or deleted file, it can cause an exception. Similarly, if you enter a digit in an array beyond the given range, the program will throw an exception. We need to handle these exceptions in Java.
It is really simple to explain exception handling in Java 8. The exception handling program in Java is managing exceptions at the programming end without showing them to the user of the application. For instance, suppose an exception occurs, and it is not handled by the programmer, then the application will show a system-generated exception message to the user. The purpose of exception handling in Java is to make the errors user-friendly.
But if we as programmers handle exceptions in the backend, then instead of the system generated message, we can show our own message in plain text. Now the users can understand the cause of the exception and provide appropriate input so that the program is executed next time without any disruption. This is the most significant reason to learn exception handling in Java programs. There is no default exception handling in Java; we need to define the relevant handling block to handle exceptions.
The biggest benefit of exception handling in Java is to maintain a program’s flow. An exception is a termination statement. This means that whenever an exception occurs in a code, the execution is stopped immediately, and the execution of the code is terminated abruptly. But if the exception is handled, then the compiler will skip only one line of the code where the exception occurs, and the rest of the code will be executed in the natural flow of the program.
To better understand how to handle exceptions in Java, let’s consider an example where a Java code has 10 statements, and an exception occurs at the 5th statement. Now, if the exception is not handled, the program will execute until the 5th statement and then will be terminated, i.e., 6th to 10th statements will not be executed. On the other hand, if the exception is handled, only the 5th statement will not be executed, and the rest of the program will work according to the flow.
Java is an OOP language; hence, even the exception class has a hierarchy. At the root of this exception handling hierarchy in Java is the ‘Throwable Class’, which is further categorized, or in the programming term, inherited by ‘Exception Class’ and ‘Error Class’. The Error Class contains all the errors that cannot be handled, such as StackOverflow Error and VirtualMachineError. The Exception Class contains all the different types of exceptions that can occur while running a Java program.
IOException, SQLException, ClassNotFoundException, and RuntimeException are all the subclasses of Exception Class. The RuntimeException Class further contains other exceptions which include, ArithmeticException, NullPointerException, NumberFormatException, and IndexOutOfBoundException.
Primarily there are two types of exception handling in Java, namely Checked Exceptions and Unchecked Exceptions. Checked Exceptions are handled at compile-time, hence the name. All the exceptions that directly inherit Throwable Class, except the Error Class and RunTime Exception, are all Checked, Exception Classes. Examples of Checked Exceptions include IOException, SQLException, and ClassNotFoundException.
Unchecked Exceptions are not handled at compile-time; instead, they are handled during the runtime. Hence, all the Classes that inherit RuntimeException are included in Unchecked Exceptions. Some of the Unchecked Exceptions include ArithmeticException, NullPointerException, NumberFormatException, and IndexOutOfBoundException.
The ‘try’ keyword is used to specify a particular block of code, where we suspect the exception to occur. Try cannot be a standalone block; hence, there must be a catch or finally block following the try block.
The ‘catch’ block is where we handle exceptions. This means that message that we want to show our users for the exception must be written in this block. It is only executed when an exception occurs and is handled. We cannot use catch as a standalone block; it has to be preceded by the try block. The use of the ‘finally’ block after the catch is optional.
The ‘final’ block includes all the important codes of the program that we want to execute, whether an exception is handled or not. It is an optional block that can be written or not depending on the need.
The ‘throw’ keyword is used to throw an exception.
The ‘throws’ keyword is used to create user-defined exception handling in Java. It is used to declare a custom exception. This keyword shows the chances of an exception occurring in a program. It is then used for custom exception handling in Java.
Exception Handling in Java is easy to understand, and with relevant examples in place, it becomes even more simple to understand. Below are some of the common syntax of exception handling in Java examples. These examples will help define exception handling in Java easily.
try {
// Â Code to try
}
catch(Exception e) {
//Â Code to handle errors
Now let’s understand exception handling with the following example.
public class RollNos {
public static void main(String[ ] args) {
int[] myRolls = {1, 2, 3};
System.out.println(myNumbers[8]); // error!
This will throw a system generated OutOfBoundEception error because we are trying to access a digit place in an array that we have not defined. The users won’t be able to understand this message. Now, let’s make the use of exception handling in this Java code.
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[8]);
} catch (Exception e) {
System.out.println(“Something went wrong.”);
This is a simple exception handling program in Java. Here the output error message will be easily understood by users.
The finally block is executed whether an exception is handled or not.
public static void main(String[] args) {
} finally {
System.out.println(“The exception handling process is completed successfully.”);
We can create custom exception handling in Java with the help of throw keywords.
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException(“Access denied – Only 18 and above age is allowed.”);
else {
System.out.println(“Access granted!”);
checkAge(13); // Set age to 13 (below 18)
This will output the Access denied message as the age is below 18. On the other hand, if we have mentioned 21 in checkAge() function, it would show Access granted message as the condition of 18 or above age is met.
Below given are some questions on exception handling in Java programming that may arise in the minds of programmers like you.
NullPointerException is a common exception that you will come across very often while programming in Java. It occurs when we try to use a reference to an object that has a null value. NullPointerException handling in Java is nothing but handling this exception.
There are chances that there might be two different exceptions that can occur in a code. That’s where Multiple exception handling in Java comes into the picture. In such a scenario, one try block can be followed by multiple catch blocks to handle multiple exceptions.
The exception handling fundamentals in Java revolve around the five keywords- try, catch, finally, throw, and throws. These keywords form the base of exception handling. All the exception handling mechanisms in Java are a result of these five keywords.
The best exception handling technique in Java is to prefer specific exceptions over the general. The concept of exception handling in Java is similar to the OOPs concept. Hence there is one class inheriting the other, we need to mention the most specific exceptions rather than general and vague exceptions. This is one of the best practices for exception handling in Java.
We hope that this blog helped answer all your questions and doubts related to exception handling in Java. Interested in learning more about Java and other Software Development tools? Check out our Master Certificate in Full Stack Development program. This online 170-hour-long course is the first & only program on Full Stack Development with Automation and AWS Cloud and is highly in demand among Full Stack learners.
Fill in the details to know more
What Is the Use of Wrapper Class in Java?
March 22, 2023
What Is Clean Coding in Java?
March 21, 2023
What Are the New Features of Java 17?
What Is File Handling in Java?
March 16, 2023
What Is Data and Time Function in Java?
March 11, 2023
Top 10 Emerging Technologies Blogs To Read In 2023
December 15, 2022
History of Java Programming Language| UNext
November 18, 2022
An Advanced Guide to Shell Scripting in Unix!
November 15, 2022
Java Tutorial For Beginners
September 28, 2022
What Is Data Abstraction?
August 24, 2022
Encapsulation In Oops With Example
August 23, 2022
Add your details:
By proceeding, you agree to our privacy policy and also agree to receive information from UNext through WhatsApp & other means of communication.
Upgrade your inbox with our curated newletters once every month. We appreciate your support and will make sure to keep your subscription worthwhile