What is Exception Handling?
Exception handling in Java is a mechanism to handle runtime errors so that the program doesnโt crash and can continue executing smoothly.
Why Exception Handling is Needed?
If you ignore exceptions, your program will:
1.Crash suddenly
2.Show ugly error messages
3.Lose user trust
With exception handling, you can:
1.Prevent crashes
2.Show meaningful messages
3.Maintain program flow
Example Without Exception Handling:
public class Test {
public static void main(String[] args) {
int a = 10;
int b = 0;
int result = a / b; // Runtime error
System.out.println(result);
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException
Example With Exception Handling:
public class Test {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int result = a / b;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
System.out.println("Program continues...");
}
}
Output :
Cannot divide by zero
Program continues...
Important Keywords in Exception Handling:
- try Contains code that may cause an exception
- catch Handles the exception
- finally Always executes (whether exception occurs or not).
try {
// risky code
} catch (Exception e) {
// handling code
} finally {
// always runs
}
Top comments (0)