Introduction

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.

  1. What are the Exceptions in Java?
  2. What is Exception Handling in Java, and Why is it Important to Learn it?
  3. What are the Advantages of Exception Handling in Java?
  4. What is Exception Hierarchy?
  5. What are Different Types of Exception Handling in Java?
  6. What are Different Exception Handling Keywords in Java?
  7. Understanding Exception Handling in Java With Examples Program
  8. Some Exception Handling Programming Questions in Java

1. What are the Exceptions in Java?

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.

2. What is Exception Handling in Java, and Why is it Important to Learn it?

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.

3. What are the Advantages of Exception Handling in Java?

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.

4. What is Exception Hierarchy?

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.

5. What are Different Types of Exception Handling in Java?

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.

6. What are Different Exception Handling Keywords in Java?

A) Try

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.

B) Catch

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.

C) Finally

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.

D) Throw

The ‘throw’ keyword is used to throw an exception.

E) Throws

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.

7. Understanding Exception Handling in Java With Examples Program

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.

A) Try…Catch Block Syntax

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.

public class RollNos {

public static void main(String[ ] args) {

try {

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.

B) Finally Block

The finally block is executed whether an exception is handled or not.

public class RollNos {

public static void main(String[] args) {

try {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[8]);

} catch (Exception e) {

System.out.println(“Something went wrong.”);

} finally {

System.out.println(“The exception handling process is completed successfully.”);

}

}

}

C) Custom Exception Handling With Throw Keyword

We can create custom exception handling in Java with the help of throw keywords.

public class RollNos {

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!”);

}

}

public static void main(String[] args) {

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.

8. Some Exception Handling Programming Questions in Java

Below given are some questions on exception handling in Java programming that may arise in the minds of programmers like you.

A) What is NullPointerException handling in Java?

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.

B) What is Multiple Exception Handling in Java?

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.

C) What are the Fundamentals of Exception Handling in Java?

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.

D) What are the Best Exception Handling Techniques in Java?

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.

Conclusion

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.

Also Read

SHARE
share

Are you ready to build your own career?