Exception Handling in Java
Today, Let's have a discussion on what is Exception? Why Exception arises, how you handle an Exception, and how can you define your own exception?
So let's begin. What is the result when you divide a number by zero? Well, most of you might think infinity is the answer. And you are right. We as humans have declared that term as infinity and infinity is something that is not defined. But the problem arises with Java Compiler and JVM. They are cannot do such calculations and as a result, they terminate the program and throws an Exception.
So basically, an abnormal or unusual condition that terminates the program at run time is called an Exception.
Error vs Exception
You must not confuse an Error with an Exception. An error will occur when the resources that the process has are not sufficient(such as stack overflow error, VM Error) whereas an Exception will occur when there is a mistake in the programming logic(such as arithmetic exception, number format exception, I/O Exception)
Hierarchy of Exception
Exception class extends from Throwable class. and further Checked and Unchecked exception extends from Exception class. You might be wondering what are these Checked and Unchecked Exceptions. Hold on we will have a discussion on this

Checked and Unchecked Exception
Checked Exceptions are those Exception which is detected during the compile time. I/O Exception, SQL Exception, and ClassNotFound Exception are checked exceptions. Whereas Unchecked Exception is detected during runtime. Arithmetic Exception, NullPointer Exception, and Index out of bound Exception are Unchecked Exceptions.
Handling Exception
Till now we have learned what Exception is and what are different types of Exception. But how to handle those exceptions. Well in java we handle Exception using 5 exception handling blocks.
- try → The block of code which can lead to an exception is written in the try block.
- catch →If an Exception has occurred the code written in this block is automatically executed.
- finally → The code written in this block is always executed irrespective of an exception has occurred or not.
- throw → The keyword throw is used to force an exception.
- throws → The keyword throws is used in the method signature which is used to instruct that the declared method might lead to one of the listed Exception.
User-Defined Exception
Can we declare our own exception? The answer is yes, Java provides us with the facility to create our own exception. For that, we have to create a class that extends from the Throwable class and inside the declared class constructor we have to call the constructor of the parent class using the super keyword.

Thank you all. I hope you enjoyed reading this blog. Any further suggestions and improvements are most welcomed.