Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
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.
When an exception occurs, and if you don’t handle it, the program will terminate abruptly (the piece of code after the line causing the exception will not get executed).
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.
An exception is a problem that arises during the execution of a program. It can occur for various reasons say-
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.
You may also go through this recording of Java Exception Handling where you can understand the topics in a detailed manner with examples.
Next, begin by understanding the 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.
Errors | Exceptions |
1. Impossible to recover from an error | 1. Possible to recover from exceptions |
2. Errors are of type ‘unchecked’ | 2. Exceptions can be either ‘checked’ or ‘unchecked’ |
3. Occur at runtime | 3. Can occur at compile time or run time |
4. Caused by the application running environment | 4. Caused by the application itself |
Now, we will dive deeper into exceptions and see how they can be handled. First, let’s see the different types of exceptions.
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.
Built-in Exceptions | Description |
ArithmeticException | It is thrown when an exceptional condition has occurred in an arithmetic operation. |
ArrayIndexOutOfBoundsException | It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array. |
ClassNotFoundException | This exception is raised when we try to 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 | It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted. |
NoSuchFieldException | It is thrown when a class does not contain the field (or variable) specified. |
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:
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); } }
Subscribe to our youtube channel to get new updates..!
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.
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:
Let’s understand each of these methods in detail.
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){}
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"); } }
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..."); } }
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"); } }
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.
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 | finally | finalize |
It is a keyword. | It is a block. | It is a method. |
Used to apply restrictions on class, methods & variables. | Used to place an important code. | Used to perform clean-up processing just before the object is garbage collected. |
final class can’t be inherited, method can’t be overridden & the variable value can’t be changed. | It will be executed whether the exception is handled or not. | – |
Similarly, throw & throws sound alike, but they are different from each other. Let’s see how, with the help of the below table.
throw | throws |
1. Used to explicitly throw an exception | 1. Used to declare an exception |
2. Checked exceptions cannot be propagated using throw only | 2. Checked exceptions can be propagated |
3. Followed by an instance | 3. Followed by a class |
4. Used within a method | 4. Used with a method signature |
5. Cannot throw multiple exceptions | 5. Can declare multiple exceptions |
//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.
Check out the Java Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.
Got a question for us? Please mention it in the comments section of this “Exception Handling” blog and we will get back to you as soon as possible.
Course Name | Date | Details |
---|---|---|
Java Course Online | Class Starts on 7th December,2024 7th December SAT&SUN (Weekend Batch) | View Details |
edureka.co