Exception Handling in Java — A Beginners Guide to Java Exceptions
Errors arise unexpectedly and can result in disrupting the normal flow of execution. This is something that every programmer faces at one point or the other while coding. Java, being the most prominent object-oriented language, provides a powerful mechanism to handle these errors/exceptions. Through this article on Java Exception Handling, I will give you a complete insight into the fundamentals and various methods of Exception Handling.
In this article, I will be covering the following topics.
- Introduction to Exception Handling
- Exceptions Hierarchy
- Basic Exception Example
- Types of Exceptions
- Exception Handling Methods
- final vs finally vs finalize
- throw vs throws
Introduction to Exception Handling
An exception is a problem that arises during the execution of a program. It can occur for various reasons say-
- A user has entered an invalid data
- File not found
- A network connection has been lost in the middle of communications
- The JVM has run out of a memory
Exception Handling mechanism follows a flow which is depicted in the below figure. But if an exception is not handled, it may lead to a system failure. That is why handling an exception is very important.
Next, begin by understanding the Exceptions Hierarchy.
Exceptions Hierarchy
All exception and error types are subclasses of class Throwable, which is the base class of hierarchy. One branch is headed by Error which occurs at run-time and other by Exception that can happen either at compile time or run-time.
Basically, an Error is used by the Java run-time system (JVM) to indicate errors that are associated with the run-time environment (JRE). StackOverflowError is an example of such an error. Whereas Exception is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception.
Now that you know what errors and exceptions are, let’s find out the basic difference between them. Take a look at the below table which draws a clear line between both of them.
Now, we will dive deeper into exceptions and see how they can be handled. First, let’s see the different types of exceptions.
- Checked Exception
It is an exception that occurs at compile time, also called compile time exceptions. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword. - Unchecked Exception
It is an exception that occurs at the time of execution. These are also called Runtime Exceptions. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to specify or catch the exceptions.
Basic Example of Exception
class Exception{
public static void main(String args[]){
try{
//code that may raise exception
}
catch(Exception e){
// rest of the program
}
}
}
Above code represent an exception wherein inside try block we are going to write a code that may raise an exception and then, that exception will be handled in the catch block.
Types of Exceptions
Built-in Exceptions
User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, a user can also create exceptions which are called ‘User-Defined Exceptions’.
Key points to note:
A user-defined exception must extend Exception class.
The exception is thrown using throw keyword.
Example:
class MyException extends Exception{
String str1;
MyException(String str2) {str1=str2;}
public String toString(){
return ("MyException Occurred: "+str1);
}
}
class Example1{
public static void main(String args[]){
try{
System.out.println("Start of try block");
throw new MyException(“Error Message");
}
catch(MyException exp){System.out.println("Catch Block");
System.out.println(exp);
}
}
Now that you have seen the different types of exceptions, let’s dive deeper into this Java Exception Handling blog to understand various methods for handling these exceptions.
Exception Handling Methods
As I have already mentioned, handling an exception is very important, else it leads to system failure. But how do you handle these exceptions?
Java provides various methods to handle the Exceptions like:
- try
- catch
- finally
- throw
- throws
Let’s understand each of these methods in detail.
try block
The try block contains a set of statements where an exception can occur. It is always followed by a catch block, which handles the exception that occurs in the associated try block. A try block must be followed by catch blocks or finally block or both.
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
Nested try block
try block within a try block is known as nested try block in java.
class Exception{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b=59/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e) {System.out.println(e);}
System.out.println("other statement);
}catch(Exception e)
{System.out.println("Exception handeled");}
System.out.println("casual flow");
}
}
catch block
A catch block is where you handle the exceptions. This block must follow the try block and a single try block can have several catch blocks associated with it. You can catch different exceptions in different catch blocks. When an exception occurs in a try block, the corresponding catch block that handles that particular exception executes.
public class Testtrycatch1{
public static void main(String args[]){
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
}
Multi-catch block
If you have to perform various tasks at the occurrence of various exceptions, you can use the multi-catch block.
public class SampleMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}
catch(Exception e)
{System.out.println("task 3 completed");}
System.out.println("remaining code");
}
}
finally block
A finally block contains all the crucial statements that must be executed whether an exception occurs or not. The statements present in this block will always execute, regardless an exception occurs in the try block or not such as closing a connection, stream etc.
class SampleFinallyBlock{
public static void main(String args[]){
try{
int data=55/5;
System.out.println(data);
}
catch(NullPointerException e)
{System.out.println(e);}
finally {System.out.println("finally block is executed");}
System.out.println("remaining code");
}
}
So, this was all about the various methods of handling exceptions.
You might have heard that final, finally and finalize are keywords in Java. Yes, they are, but they differ from each other in various aspects. So, let’s see how final, finally and finalize are different from each other with the help of below table.
final vs finally vs finalize
Similarly, throw & throws sound alike, but they are different from each other. Let’s see how, with the help of the below table.
throw vs throws
//Java throw example
void a()
{
throw new ArithmeticException("Incorrect");
}
//Java throws example
void a()throws ArithmeticException
{
//method code
}
//Java throw and throws example
void a()throws ArithmeticException
{
throw new ArithmeticException("Incorrect");
}
This brings us to the end of our blog on Exception Handling in Java. I hope you found this blog informative and added value to your knowledge.
If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.
Do look out for other articles in this series which will explain the various other aspects of Java.
1. Object Oriented Programming
5. Java String
6. Java Array
8. Java Threads
9. Introduction to Java Servlets
11. Java Tutorial
14. Java Programs
15. Kotlin vs Java
16. Dependency Injection Using Spring Boot
22. Socket Programming In Java
25. Library Management System Project in Java
26. Trees in Java
28. Top Data Structures & Algorithms in Java
30. Top 55 Servlet Interview Questions
34. Java Collections Interview Questions and Answers
35. How to Handle Deadlock in Java?
36. Top 50 Java Collections Interview Questions You Need to Know
37. What is the concept of String Pool in Java?
38. What is the difference between C, C++, and Java?
39. Palindrome in Java- How to check a number or string?
40. Top MVC Interview Questions and Answers You Need to Know
41. Top 10 Applications of Java Programming Language
42. Deadlock in Java
43. Square and Square Root in Java
Originally published at www.edureka.co on November 28, 2018.