Exception handling in Java

Anojan Vanniyasingam
2 min readJul 22, 2022

Exception handling in java makes the error handing clear and well-lit for addressing “exceptional situations” that happen during runtime. It is based on your knowledge of the method’s risk, allowing you to design code to handle it.

A try/catch block tells the compiler that you know an exceptional thing could happen in the method you’re calling, and that you’re prepared to handle it. That compiler doesn’t care how you handle it; it cares only that you say you’re taking care of it

What is an Exception?

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception. The exception class is a subclass of the Throwable class and Exceptions can be divided into two main groups. The first one is a Checked Exception and the other one is an Unchecked Exception.

Unchecked Exception vs Checked Exception

Source: rollbar.com

When we compile a program, The compiler checks everything except Runtime Exception. The Runtime Exception is known as an unchecked exception. You can throw, catch and declare a Runtime Exception but, the compiler doesn’t care. And Runtime Exception is also a subclass of Exception and all other unchecked exceptions are subclasses of the Runtime Exception. Here are some example of unchecked exceptions: NullPointerException, ClassCastException, ArithmeticException, IndexOutOfBounsException.

A checked exception in Java is something that has gone wrong in your code and is potentially recoverable. For example, if there’s a client error when calling another API, we could retry from that exception and see if the API is back up and running the second time. A checked exception is caught at compile time so if something throws a checked exception the compiler will enforce that you handle it.

Here are some examples of the checked exception.

ClassNotFoundException,IOException

Points to note when we work with exceptions.

· A method can throw an exception when something fails at runtime

· You cannot have a catch or finally block without try block.

· A method throws an exception with the keyword throw, followed by a new exception object.

· You cannot put the codes between try and catch blocks.

· try block must be with finally or catch block.

--

--