Exception handling is one of the vital features in java programming, which deals with a run-time error during an execution of a program, and the program’s normal flow disrupts. As we all know, compile-time is the best time to deal with the errors in a java program so that it executes well at run time, but all errors cannot be detected at compile-time and may arise at run time. Now, these run time errors are known as exceptions.
Why an Exception occurs?
There can be several reasons which lead a program to throw an exception. For example: Opening a non-existing file in your program, Network connection problem, bad input data provided by the user, JVM run out of memory etc.
What is Exception Handling?
Java provides a robust and object-oriented way to handle exceptions such as ClassNotFound Exception, IO Exception, SQL Exception, Remote Exception, known as Java Exception Handling. For example- a program input two integer values from the user at run time for division. Here we can assume that the denominator would be zero value. It will generate an Arithmetic Exception. The control is redirected to someplace of code to handle the problem; that place is an exception handler.
Whenever an exception occurs during program execution, it creates an exception object. Then, the program’s normal flow draws to a stand, and the JRE tries to find someone that can handle the raised exception. The exception object has a lot of debugging information such as method hierarchy, the line number of the exception occurrence, type of the exception etc. Whenever 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”.
Exception Handling in Java – Useful Methods
In the Exception handling mechanism, all methods are defined in the base class, i.e. Throwable class. The exception classes are created to specify the different kinds of exception scenarios so that we can comfortably identify the root cause and handle the exception according to its type
Some of the useful methods of Throwable class are;
- public String getMessage() – This method returns the string message stored in detailMessage variable.
- public String toString() – This method returns the information about Throwable in String format; the returned string contains the name of the Throwable class and localised message.
- public void printStackTrace() – This method prints the stack trace information to the standard error stream; it shows the information about invoked methods from the runtime stack.
- public StackTraceElementgetStackTrace() – It returns an array of stack trace elements ,each represents one stack frame.
java.lang.Throwable Class Hierarchy
java.lang.Throwable class is the main class from which all exceptions are derived in java. Further, it can be divided into two parts, i.e. Exception and Error.
|ArithmeticException||It is thrown when an exceptional condition has occurred in an arithmetic operation like “/by zero”.|
|ClassNotFoundException||This exception is raised when we access a class whose definition is not found.|
|FileNotFoundException||An exception that is raised when a file is not accessible or does not open.|
|IOException||It is thrown when an input-output operation is failed or interrupted.|
|InterruptedException||The Interrupted exception is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.|
Types of Exception in java
There are fundamentally two types of exceptions:
- Checked Exceptions
- Unchecked Exceptions
1. Checked Exceptions: All exceptions, which are direct subclasses of exception class except RunTime exception and Error class, are known as checked exceptions. For example: SQLException, IOException, FileNotFoundException etc.
2. Unchecked Exceptions: All exceptions derived from RunTime Exception and Error class directly or indirectly are known as Unchecked Exceptions. For example: ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException, IOError, AWTError.
Java Exception Handling Keywords
1. Using try-catch Block: To protect the code from exceptions, we must write the dubious code in a try block, followed by catch block and finally block. The catch block handles the exception and must be preceded by a try block. It means you can’t use the try block and catch block alone. The catch block is known as an exception handler.
2. Using finally Block: A finally block is used to execute a necessary code in a program, whether an exception occurs or not. It means code present in finally block always execute whether an exception occurs in try-catch block handled or not. Here, finally block used with try-catch block.
3. Using Throw Keyword:
If you don’t want to handle the exception yourself or generate your exceptions for others to handle, then throw keyword can be used. The throw keyword can be used with subclasses of Throwable classes only.
throw new Exception(“Exception message”);
4. Using Multiple catch Blocks: A try block can throw multiple exceptions. It depends upon the tasks performed inside the try block. As we know that one catch block handles a specific type of exception. So to handle multiple exceptions, we can use multiple catch blocks with different exception classes.
Let’s see some programming code examples using the Exception Handling mechanism:
1. The following program is written using a try-catch block:
welcome to the java world
this code is not valid
From the above program, we can say that a program can be executed well with the exception handling mechanism without any termination. In the above program, when an exception occurs, JVM creates an ArithmeticException class object and throws reference in the catch block to handle the exception.
2. The following program is written using the finally block:
Start coding now
finally code has been executed successfully
3. The next program is written using the throw keyword:
do not divide with zero
This brings us to the end of the blog on Exception Handling in Java. Hope this helps you to up-skill your C++ skills. To learn more about programming and other related concepts, check out the courses on Great Learning Academy.
Also, if you are preparing for Interviews, check out these Interview Questions for Java to ace it like a pro.1