Exception Handling in java

Ratings:
(4)
Views:0
Banner-Img
  • Share this blog:

What is Exception Handling in java?

The exception is an error event that can happen during the execution of a program and disrupts its normal flow. Java provides a robust and object-oriented way to handle exception scenarios, known as Java Exception Handling.

Java is an object-oriented programming language, whenever an error occurs while executing a statement, creates an exception object and then the normal flow of the program halts and JRE tries to find someone that can handle the raised exception. The exception object contains a lot of debugging information such as method hierarchy, line number where the exception occurred, type of exception etc. When the exception occurs in a method, the process of creating the exception object and handing it over to the runtime environment is called “throwing the exception”.

Table of Contents

What is an error in Java?

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.

What is exception hierarchy in Java?

Exception Hierarchy: All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.

What is the base class for all exceptions?

Firstly, the base class of all things that can be thrown is Throwable (not Exception ). Under Throwable are two subclasses: Exception and Error. Of these 4 main classes, RuntimeException and Error are unchecked (may be thrown without having to be declared as being thrown).

Why do we use Exception Handling?

Handling the exception is nothing but converting system error-generated messages into user-friendly error messages. Whenever an exception occurs in the java application, JVM will create an object of appropriate exception of subclass and generates a system error message, these system-generated messages are not understandable by the user so need to convert it into a user-friendly error message. You can convert system error messages into user-friendly error messages by using the exception handling feature of java.

For Example: when you divide any number by zero the system generates / by zero so this is not understandable by the user you can convert this message into a user-friendly error message like Don't enter zero for the denominator.

Exception Handling in java

Type of Exception

  • Checked Exception
  • Un-Checked Exception

Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.

Unchecked Exception

The classes that extend Runtime Exception are known as unchecked exceptions e.g. Arithmetic Exception, NullPointerException, Array Index Out Of Bounds Exception etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

Java Exception Handling Keywords

There are 5 keywords used in java exception handling.

  • throw: We know that if any exception occurs, an exception object is getting created and then Java runtime starts processing to handle them. Sometime we might want to generate exception explicitly in our code, for example in a user authentication program we should throw exception to client if the password is null. throw keyword is used to throw exception to the runtime to handle it.
  • throws: When we are throwing any exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it’s caller method using throws keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also.
  • try-catch: We use try-catch block for exception handling in our code. try is the start of the block and catch is at the end of try block to handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be nested also. catch block requires a parameter that should be of type Exception.
  • finally: finally block is optional and can be used only with try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block. finally block gets executed always, whether exception occurred or not.

Syntax for handling the exception

try
{
  // statements cause problems at run time 
}
catch(type of exception-1 object-1)
{
  // statements provide a user-friendly error message 
}
catch(type of exception-2 object-2)
{
  // statements provide a user-friendly error message
}
finally
{
  // statements that will execute compulsory 
}
Example without Exception Handling
class ExceptionDemo 
{
public static void main(String[] args) 
{
int a=10, ans=0;
ans=a/0;
System.out.println("Denominator not be zero");		
}
}

Example of Exception Handling

class ExceptionDemo 
{
public static void main(String[] args) 
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch (Exception e)
{
System.out.println("Denominator not be zero");
}	
}
}

Output:

Denominator not be zero

Java Exception Hierarchy

As stated earlier, when any exception is raised an exception object is getting created. Java Exceptions are hierarchical and inheritance is used to categorize different types of exceptions. Throwable is the parent class of Java Exceptions Hierarchy and it has two child objects – Error and Exception. Exceptions are further divided into checked exceptions and runtime exception.

  • Errors: Errors are exceptional scenarios that are out of scope of application and it’s not possible to anticipate and recover from them, for example hardware failure, JVM crash or out of memory error. That’s why we have a separate hierarchy of errors and we should not try to handle these situations. Some of the common Errors are OutOfMemoryError and StackOverflowError.
  • Checked Exceptions: Checked Exceptions are exceptional scenarios that we can anticipate in a program and try to recover from it, for example FileNotFoundException. We should catch this exception and provide useful message to user and log it properly for debugging purpose. Exception is the parent class of all Checked Exceptions and if we are throwing a checked exception, we must catch it in the same method or we have to propagate it to the caller using throws keyword.
  • Runtime Exception: Runtime Exceptions are cause by bad programming, for example trying to retrieve an element from the Array. We should check the length of array first before trying to retrieve the element otherwise it might throw ArrayIndexOutOfBoundException at runtime. RuntimeException is the parent class of all runtime exceptions. If we are throwing any runtime exception in a method, it’s not required to specify them in the method signature throws clause. Runtime exceptions can be avoided with better programming.

Exception Handling in java

For indepth understanding of Java Click on:

Java Tutorials

You liked the article?

Like : 0

Vote for difficulty

Current difficulty (Avg): Medium

Recommended Courses

1/15

About Author
Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.


Stay Updated


Get stories of change makers and innovators from the startup ecosystem in your inbox