Exception Handling
Exception handling in Java is a powerful mechanism to handle runtime errors, ensuring that the normal flow of the application can be maintained. Let’s dive into the details:
Basic Exception Method
package com.siteinvokers;
public class ExceptionHandling {
public static void main(String[] args) {
// This method will throw a null pointer exception with stacktrace
method1();
//Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "str" is null
//at com.siteinvokers.ExceptionHandling.method2(ExceptionHandling.java:19)
//at com.siteinvokers.ExceptionHandling.method1(ExceptionHandling.java:13)
//at com.siteinvokers.ExceptionHandling.main(ExceptionHandling.java:8)
}
private static void method1() {
method2();
}
private static void method2() {
// Null pointer exception
String str = null;
str.length();
// Exception in thread "main" java.lang.NullPointerException: Cannot invoke
// "String.length()" because "str" is null
// at com.siteinvokers.ExceptionHandeling.main(ExceptionHandeling.java:9)
}
}
What is an Exception in Java?
- An exception is an abnormal condition that disrupts the normal flow of a program. It occurs during runtime and is represented as an object.
- Examples of exceptions include
ClassNotFoundException
,IOException
,SQLException
, andRemoteException
.
What is Exception Handling?
- Exception handling is a mechanism to deal with runtime errors.
- When an exception occurs within a method, it creates an exception object containing information about the exception.
- The goal is to maintain the normal flow of the application.
Advantages of Exception Handling
- Ensures that the program doesn’t crash abruptly.
- Allows graceful handling of unexpected events.
- Prevents unhandled exceptions from halting execution.
Hierarchy of Java Exception Classes:
- The root class is
java.lang.Throwable
, inherited by two subclasses:Exception
andError
. Exception
is used for exceptional conditions that user programs should catch (e.g.,NullPointerException
).Error
is used by the JVM to indicate errors related to the runtime environment (e.g.,StackOverflowError
).
Types of Exceptions
- Checked Exceptions: Checked at compile-time (e.g.,
IOException
,SQLException
). - Unchecked Exceptions: Not checked at compile-time (e.g.,
ArithmeticException
,NullPointerException
).
Handling the Exception
We will handle the exception using try and catch block
ExceptionHandlingTryCatch.java file
package com.siteinvokers;
public class ExceptionHandlingTryCatch {
public static void main(String[] args) {
method1();
System.out.println("Main method ended");
}
private static void method1() {
method2();
System.out.println("Method 1 ended");
}
private static void method2() {
try {
// Null pointer exception
String str = null;
str.length();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println("Method 2 ended");
}
}
Handling the Exception and Finally Block
Finally block is the block that will always execute, whether an exception occurs or not.
Finally block will not execute only when JVM crash happens like you add System.exit(1) command before finally block.
It will execute even if we add a return statement before finally block.
FinallyRunner.java file
package com.siteinvokers;
import java.util.Scanner;
public class FinallyRunner {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
try {
int[] num = { 1, 2, 3 };
int nm = num[4];
System.out.println("Inside try");
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Before scanner close");
sc.close();
}
System.out.println(" Before main close");
}
}
Checked Exception
Checked exceptions in Java are those exceptions that the compiler verifies at compile-time. They represent errors outside the control of the program and force developers to handle them explicitly. Let’s explore them further:
- They are a subclass of InterruptedException
- Checked exceptions are verified by the Java compiler during compilation.
- They must be either caught using a
try-catch
block or declared in the method signature using thethrows
keyword. - Examples of checked exceptions include:
IOException
: Thrown for input/output errors (e.g., file not found).SQLException
: Related to database operations.ParseException
: Occurs during parsing of data.
When to Use Checked Exceptions:
- Use checked exceptions when a client can reasonably recover from the exception.
- They help separate error-handling code from regular code.
- By following this practice, we ensure robust and reliable Java applications.
Remember, checked exceptions play a crucial role in maintaining code integrity and handling exceptional conditions!
FinallyRunner.java file
Un-Checked Exception
Unchecked exceptions in Java are those exceptions that are not checked by the compiler during compilation. They are also known as runtime exceptions. Unlike checked exceptions, which are verified at compile-time, unchecked exceptions come into play and occur during program execution when buggy code is encountered.
Here are some key points about unchecked exceptions:
Examples of Unchecked Exceptions:
- They are a subclass of Runtime exceptions.
- There is no need of try and catch block in it.
- These exceptions are usually caused by programming errors or unexpected conditions.
- Some common unchecked exceptions in Java include:
ArithmeticException
: Thrown when dividing by zero or performing invalid arithmetic operations.NullPointerException
: Occurs when attempting to access a null object reference.ArrayIndexOutOfBoundsException
: Thrown when accessing an array index that is out of bounds.IllegalArgumentException
: Raised when an illegal argument is passed to a method.
Custom Exception
- Custom exceptions are exceptions that are created by the user as per the need.
- To create a custom exception we create a new class that extends the Exception class, and the class or method which throws the exception has to use try-catch block or throws that exception.
FinallyRunner.java file
package com.siteinvokers;
import java.util.Scanner;
public class FinallyRunner {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
try {
int[] num = { 1, 2, 3 };
int nm = num[4];
System.out.println("Inside try");
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Before scanner close");
sc.close();
}
System.out.println(" Before main close");
}
}
Try With Resource
- In this, we add a resource that is auto-closable in try method.
- This will automatically close the scanner no need to close it.
- There is no need of catch and finally block also, if u want u can add that
TryWithResourcesRunner.java file
package com.siteinvokers;
import java.util.Scanner;
public class TryWithResourcesRunner {
public static void main(String[] args) {
// TODO Auto-generated method stub
// this will automatically close the the scanner no need to close it
// there is no need of catch and finally block also, if u want u can add that
try(Scanner sc = new Scanner(System.in)){
int[] num = { 1, 2, 3 };
int nm = num[4];
}
System.out.println(" Before main close");
}
}