What is Exception Handling?
Exception handling is a mechanism to handle runtime errors so your program doesn’t crash abruptly.
- Prevents Program Crash
Without exception handling, your program stops immediately when an error occurs.
❌ Without Exception Handling:
int a = 10;
int b = 0;
System.out.println(a / b); // Crash: ArithmeticException
System.out.println("Program continues"); // Never runs
✅ With Exception Handling:
try {
int a = 10;
int b = 0;
System.out.println(a / b);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
System.out.println("Program continues");
2.Maintains Normal Program Flow :
Even if an error happens, the rest of the code still runs.
try {
int arr[] = {1, 2, 3};
System.out.println(arr[5]); // Error
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid index");
}
System.out.println("Next task executed");
3.Separating Error-Handling Code from "Regular" Code
-Normal Code :
errorCodeType readFile {
initialize errorCode = 0;
open the file;
if (theFileIsOpen) {
determine the length of the file;
if (gotTheFileLength) {
allocate that much memory;
if (gotEnoughMemory) {
read the file into memory;
if (readFailed) {
errorCode = -1;
}
} else {
errorCode = -2;
}
} else {
errorCode = -3;
}
close the file;
if (theFileDidntClose && errorCode == 0) {
errorCode = -4;
} else {
errorCode = errorCode and -4;
}
} else {
errorCode = -5;
}
return errorCode;
}
Exception with code :
readFile {
try {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
} catch (fileOpenFailed) {
doSomething;
} catch (sizeDeterminationFailed) {
doSomething;
} catch (memoryAllocationFailed) {
doSomething;
} catch (readFailed) {
doSomething;
} catch (fileCloseFailed) {
doSomething;
}
}
-
Helps in Debugging :
You can print error details to understand the problem.
try {
int a = 5 / 0;
} catch (Exception e) {
e.printStackTrace();
}
- It Shows exact error and line number.
- Allows Custom Error Messages :
-You can give meaningful feedback instead of cryptic errors.
User-friendly error handling.
try {
int age = -5;
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
Top comments (0)