Java
EXCEPTION IN JAVA
Exception
An Exception is an unexpected event that occurs during program
execution and disrupts the normal flow of the program.
Simple definition:
◦ Exception = Runtime error that stops normal program execution
Example Exception
public class Test {
public static void main(String[] args) {
int a = 10;
int b = 0;
int c = a / b;
[Link](c);
}
}
Output
Exception in thread "main" [Link]: / by zero
What happened?
10 / 0 → not possible
So Java throws
ArithmeticException
Program crashes immediately.
What is Exception Handling
Exception handling means handling runtime errors so that program
execution continues normally.
Program runs
↓
Error occurs
↓
Exception handled
↓
Program continues
Why Exception Handling is Needed
Without exception handling:
Program crash
With exception handling:
Program continues execution
Advantages:
• Prevent program crash
• Maintain normal program flow
• Improve program reliability
• Handle runtime errors properly
Types of Errors in Java
Java has 3 types of errors.
Type Description
Compile-time error Occurs during compilation
Runtime error Occurs during execution
Logical error Program runs but gives wrong result
Compile-time error
int a = "hello";
Runtime error
10 / 0
Logical error
Area formula written wrong
Exception Hierarchy
All exceptions come from Throwable class.
Object
|
Throwable
|
---------------------------------------------
| |
Error Exception
|
-------------------------------
| |
Checked Exception Unchecked Exception
Throwable class
The Throwable class is the superclass (parent class) of all errors and exceptions in Java.
Throwable = Root class of all exceptions and errors
Whenever a problem occurs in Java, the JVM creates an object of a class that extends Throwable.
Explanation:
• Error → Serious problems (JVM level)
• Exception → Problems that programs can handle
Two Main Subclasses of Throwable
Error
Errors represent serious problems that usually cannot be handled by
a program.
Examples
OutOfMemoryError
StackOverflowError
VirtualMachineError
int[] arr = new int[1000000000];
OutOfMemoryError
Exception
Exceptions represent conditions that programs can handle.
Examples
ArithmeticException
NullPointerException
IOException
ArrayIndexOutOfBoundsException
int a = 10/0; ///// ArithmeticException
Why Throwable Class Exists
The purpose of Throwable is to provide common functionality for errors and exceptions.
It provides methods like:
• printStackTrace()
• getMessage()
• toString()
Important Methods of Throwable
Method Description
printStackTrace() Prints error details
getMessage() Returns error message
Returns exception name and
toString()
message
getCause() Returns cause of exception
printStackTrace()
printStackTrace() prints the complete error details including:
•Exception name
•Error message
•Line number
•Method call sequence
It helps programmers debug the program.
public class Test1 {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int result = a / b; // error
[Link](result);
} catch (ArithmeticException e) {
[Link]();
} Output
} [Link]: / by zero
at [Link]([Link])
getMessage()
returns only the error message, not the full details.
public class Test2 { catch (ArithmeticException e) {
public static void main(String[] args) { [Link]([Link]());
try { }
int a = 10; }
int b = 0; }
int result = a / b;
}
Output
/ by zero
toString()
toString() returns: ExceptionName + Message
public class Test3 { catch (ArithmeticException e) {
public static void main(String[] args) { [Link]([Link]());
try { }
int a = 10; }
int b = 0; }
int result = a / b;
Output
} [Link]: / by zero
getCause()
getCause() returns the original cause of the exception.
Sometimes one exception is caused by another exception.
public class Test4 { }
public static void main(String[] args) { }
try { catch (Exception e) {
try { [Link]("Cause of Exception: " +
int a = 10 / 0; [Link]());
}
}
catch (ArithmeticException e) {
}
throw new Exception("New Exception Occurred", e); }
Output
Cause of Exception: [Link]: / by zero
ArithmeticException → original error
Exception → new exception created
public class Test {
public static void main(String[] args) {
try {
int a = 10/0;
}
catch (Throwable t) {
[Link]([Link]());
[Link]();
}
}
}
You can catch any error or exception using Throwable.
try {
int a = 10/0;
}
catch (Throwable t) {
[Link]("Error occurred");
}
But generally not recommended, because it catches both Errors and Exceptions.
Key Points about Throwable
[Link] is the parent class of all exceptions and errors
[Link] is present in [Link] package
[Link] main subclasses:
•Error
•Exception
[Link] provides methods for error information and debugging
Types of Exceptions
Java exceptions are two types.
Type Description
Checked Exception Checked at compile time
Unchecked Exception Occurs at runtime
Checked Exceptions
Checked by
compiler.
Program must handle them using try-catch or throws.
Examples
IOException
SQLException
FileNotFoundException
Unchecked Exception
Occur at runtime.
Compiler does not force handling.
Examples
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
Common Exceptions in Java
Exception Cause
ArithmeticException Divide by zero
NullPointerException Using null object
ArrayIndexOutOfBoundsException Invalid array index
NumberFormatException Wrong number format
ClassCastException Invalid type casting
Exception Handling Keywords
Java provides 5 keywords for exception handling.
Keyword Purpose
block where exception may
try
occur
catch handles exception
finally always executes
throw used to throw exception
throws declares exception
try-catch Example
public class Test {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int c = a / b;
[Link](c);
}
catch (ArithmeticException e) {
[Link]("Cannot divide by
zero");
}
}
}
Execution Flow
Program Start
↓
try block executed
↓
Exception occurs
↓
catch block handles exception
↓
Program continues
Multiple catch blocks for one try
A program can have multiple catch blocks.
try {
int arr[] = new int[5];
arr[10] = 50;
catch (ArithmeticException e) {
[Link]("Arithmetic error");
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index error");
}
import [Link].*;
public class MultiCatchExample {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int c = a / b; // ArithmeticException
int arr[] = {1,2,3};
[Link](arr[5]); //
ArrayIndexOutOfBoundsException
String s = null;
[Link]([Link]()); // NullPointerException
}
catch (ArithmeticException e) {
[Link]("Arithmetic Exception
Occurred");
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array Index Out Of Bounds");
}
catch (NullPointerException e) {
[Link]("Null Pointer Exception");
}
}
}
Output
Arithmetic Exception Occurred
Why only one message?
Because after the first exception occurs, the rest of the try block does not execute.
Multiple try–catch Blocks in One Program
Here each error is handled separately.
public class MultipleTryExample {
public static void main(String[] args) {
// First try
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Divide by zero
error");
}
// Second try
try {
int arr[] = {1,2,3};
[Link](arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index error");
}
// Third try
try {
String s = null;
[Link]([Link]());
} catch (NullPointerException e) {
[Link]("Null object error");
}
[Link]("Program continues normally");
}
}
Type Description
Handles multiple possible exceptions in
One try + many catch
same block
Many try–catch Handles each error separately
Finally Block
finally block always executes.
try {
int a = 10/0;
}
catch (Exception e) {
[Link]("Error occurred");
}
finally {
[Link]("Program finished");
}
throws Keyword
throws is used to declare exceptions in method signature
import [Link].*;
public class ThrowsExample {
static void readFile() throws IOException {
FileReader file = new FileReader("[Link]");
}
public static void main(String[] args) {
try{
readFile();
}
catch(IOException e){
[Link]("File not found");
}
}
}
throw Keyword
throw is used to manually create and throw an exception.
public class ThrowExample {
public static void main(String[] args) {
int age = 15;
if(age < 18){
throw new ArithmeticException("You are not eligible");
}
[Link]("You can vote");
}
}
Output
Exception in thread "main" [Link]: You are not eligible
Real Life Example
ATM Machine
Withdraw money
↓
Balance < withdrawal
↓
Exception throw
↓
"Insufficient Balance"
ArithmeticException
Occurs when a mathematical error happens (like divide by zero).
public class ArithmeticExample {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int c = a / b; // error
[Link](c);
} catch (ArithmeticException e) {
[Link]("Cannot divide by
zero");
}
}
Output
} Cannot divide by zero
NullPointerException
Occurs when using an object that is null.
public class NullExample {
public static void main(String[] args) {
try {
String name = null;
[Link]([Link]());
} catch (NullPointerException e) {
[Link]("Object is null");
}
}
} Output
Object is null
ArrayIndexOutOfBoundsException
Occurs when array index is outside range.
public class ArrayExample {
public static void main(String[] args) {
try {
int arr[] = {10,20,30};
[Link](arr[5]);
} catch (ArrayIndexOutOfBoundsException
e) {
[Link]("Invalid array index");
}
}
} Output
Invalid array index
NumberFormatException
Occurs when string cannot convert to number.
public class NumberFormatExample {
public static void main(String[] args) {
try {
int num = [Link]("abc");
[Link](num);
} catch (NumberFormatException e) {
[Link]("Invalid number
format");
}
}
} Output
Invalid number format
ClassCastException
Occurs when wrong type casting happens.
public class CastExample {
public static void main(String[] args) {
try {
Object obj = "Hello";
Integer num = (Integer) obj;
} catch (ClassCastException e) {
[Link]("Invalid type
casting");
}
}
} Output
Invalid type casting
StringIndexOutOfBoundsException
Occurs when string index is invalid
public class StringExample {
public static void main(String[] args) {
try {
String s = "Java";
[Link]([Link](10));
} catch (StringIndexOutOfBoundsException
e) {
[Link]("Invalid string
index");
}
}
} Output
Invalid string index
InputMismatchException
Occurs when wrong input type is entered.
import [Link];
public class InputExample {
public static void main(String[] args) {
try {
Scanner sc = new Scanner([Link]);
[Link]("Enter number:");
int num = [Link]();
} catch (InputMismatchException e) {
[Link]("Enter only
numbers");
}
}
}
FileNotFoundException
Occurs when file does not exist.
import [Link].*;
public class FileExample {
public static void main(String[] args) {
try {
FileReader file = new
FileReader("[Link]");
} catch (FileNotFoundException e) {
[Link]("File not found");
}
}
}