Exception Handling in Java – Complete Guide
(Theory + Practical + Problems)
1. What is Exception Handling in Java?
Theory
Exception Handling is a mechanism in Java used to handle runtime errors so that the normal flow of the
program can be maintained. An exception is an unexpected event that occurs during program execution.
Examples: - Dividing a number by zero - Accessing an invalid array index - Trying to open a file that does not
exist
Java provides a robust exception handling framework using: - try - catch - finally - throw -
throws
Why Exception Handling is Important?
• Prevents program termination
• Separates error-handling code from normal logic
• Improves reliability and readability
• Useful for debugging
2. Error vs Exception
Theory
Error Exception
Serious problems Recoverable problems
Occur due to system failure Occur due to program logic
Cannot be handled Can be handled
Part of [Link] Part of [Link]
Examples
Errors: - OutOfMemoryError - StackOverflowError
Exceptions: - ArithmeticException - NullPointerException - IOException
1
Practical Example
public class ErrorVsException {
public static void main(String[] args) {
int a = 10, b = 0;
[Link](a / b); // ArithmeticException
}
}
3. Default Exception Handler
Theory
When an exception occurs and is not handled by the programmer, JVM provides a default exception
handler.
Default handler: - Prints exception name - Prints description - Prints stack trace - Terminates program
Practical Example
public class DefaultHandler {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
[Link](arr[5]);
}
}
Output
Exception in thread "main" [Link]
4. Exception Handling Using try and catch
Theory
try block contains risky code. catch block handles the exception.
Syntax:
2
try {
// risky code
} catch(ExceptionType e) {
// handling code
}
Practical Example
public class TryCatchDemo {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
}
[Link]("Program continues");
}
}
Problem
Q: Handle input mismatch when user enters a string instead of a number.
Solution
import [Link];
public class InputMismatchDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try {
[Link]("Enter number: ");
int n = [Link]();
[Link]("Number: " + n);
} catch (Exception e) {
[Link]("Invalid input");
}
}
}
3
5. Multiple catch Blocks
Theory
Multiple catch blocks are used to handle different exceptions separately.
Rules: - Specific exceptions must come first - General exception last
Practical Example
public class MultipleCatch {
public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[10] = 50;
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index error");
} catch (Exception e) {
[Link]("General exception");
}
}
}
6. Exception Handling Using throws Declaration
Theory
throws keyword is used to declare exceptions that a method may pass to the caller.
Used mainly for checked exceptions.
Syntax:
returnType methodName() throws ExceptionType
Practical Example
import [Link].*;
public class ThrowsDemo {
static void readFile() throws IOException {
4
FileReader fr = new FileReader("[Link]");
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
[Link]("File not found");
}
}
}
Problem
Q: Create a method that throws ArithmeticException.
Solution
class Demo {
static void divide(int a, int b) throws ArithmeticException {
[Link](a / b);
}
}
7. Exception Handling Using throw Declaration
Theory
throw keyword is used to explicitly throw an exception.
Syntax:
throw new ExceptionType("message");
Practical Example
public class ThrowDemo {
static void validateAge(int age) {
if (age < 18)
throw new ArithmeticException("Not eligible");
else
[Link]("Eligible");
5
}
public static void main(String[] args) {
validateAge(15);
}
}
8. Hierarchy of Exception
Theory
All exceptions inherit from Throwable .
Hierarchy:
Throwable
├── Error
└── Exception
├── RuntimeException
│ ├── ArithmeticException
│ ├── NullPointerException
│ └── ArrayIndexOutOfBoundsException
└── IOException
Types of Exceptions
• Checked Exceptions: Compile-time (IOException)
• Unchecked Exceptions: Runtime (NullPointerException)
9. Custom Exception Handling (User Defined Exception)
Theory
User-defined exceptions are created by extending Exception class.
Used when built-in exceptions are not sufficient.
Steps to Create Custom Exception
1. Extend Exception
2. Create constructor
6
3. Use throw
Practical Example
class InvalidMarksException extends Exception {
InvalidMarksException(String msg) {
super(msg);
}
}
public class CustomExceptionDemo {
static void checkMarks(int marks) throws InvalidMarksException {
if (marks < 0 || marks > 100)
throw new InvalidMarksException("Invalid marks");
else
[Link]("Valid marks");
}
public static void main(String[] args) {
try {
checkMarks(120);
} catch (InvalidMarksException e) {
[Link]([Link]());
}
}
}
Problem
Q: Create a custom exception for insufficient balance.
Solution
class InsufficientBalanceException extends Exception {
InsufficientBalanceException(String msg) {
super(msg);
}
}
10. Interview-Oriented Problems
Problem 1
What happens if exception is not handled?
7
Answer: Default exception handler terminates program.
Problem 2
Can we have try without catch?
Answer: Yes, with finally.
Problem 3
Difference between throw and throws?
throw throws
Used inside method Used in method declaration
Throws one exception Declares multiple exceptions
11. Summary
• Exception handling prevents runtime failure
• try-catch handles exceptions
• throw explicitly throws exception
• throws declares exception
• Custom exceptions improve clarity
12. Assignment Programs – Solutions (15 Programs)
Assignment 1: Arithmetic Exception Handling
class Assign1 {
public static void main(String[] args) {
try {
int a = 10, b = 0;
[Link](a / b);
} catch (ArithmeticException e) {
[Link]("Division by zero not allowed");
}
}
}
8
Assignment 2: ArrayIndexOutOfBoundsException
class Assign2 {
public static void main(String[] args) {
try {
int[] arr = {1,2,3};
[Link](arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Invalid array index");
}
}
}
Assignment 3: NullPointerException
class Assign3 {
public static void main(String[] args) {
try {
String s = null;
[Link]([Link]());
} catch (NullPointerException e) {
[Link]("Null reference accessed");
}
}
}
Assignment 4: Multiple Catch Blocks
class Assign4 {
public static void main(String[] args) {
try {
int a = 10/0;
} catch (ArithmeticException e) {
[Link]("Arithmetic error");
} catch (Exception e) {
[Link]("General exception");
}
}
}
9
Assignment 5: Finally Block
class Assign5 {
public static void main(String[] args) {
try {
int a = 10/2;
[Link](a);
} catch (Exception e) {
[Link]("Exception occurred");
} finally {
[Link]("Finally block executed");
}
}
}
Assignment 6: throws Keyword
import [Link].*;
class Assign6 {
static void readFile() throws FileNotFoundException {
FileReader fr = new FileReader("[Link]");
}
public static void main(String[] args) {
try {
readFile();
} catch (Exception e) {
[Link]("File not found");
}
}
}
Assignment 7: throw Keyword
class Assign7 {
static void validateAge(int age) {
if(age < 18)
throw new ArithmeticException("Not eligible to vote");
[Link]("Eligible to vote");
}
public static void main(String[] args) {
10
validateAge(16);
}
}
Assignment 8: Custom Exception – Marks Validation
class InvalidMarksException extends Exception {
InvalidMarksException(String msg){ super(msg); }
}
class Assign8 {
static void checkMarks(int m) throws InvalidMarksException {
if(m < 0 || m > 100)
throw new InvalidMarksException("Invalid marks");
[Link]("Valid marks");
}
public static void main(String[] args) {
try {
checkMarks(120);
} catch(Exception e) {
[Link]([Link]());
}
}
}
Assignment 9: Banking – Insufficient Balance
class InsufficientBalanceException extends Exception {
InsufficientBalanceException(String msg){ super(msg); }
}
class Assign9 {
static void withdraw(int bal,int amt) throws InsufficientBalanceException {
if(amt > bal)
throw new InsufficientBalanceException("Insufficient balance");
[Link]("Withdrawal successful");
}
public static void main(String[] args) {
try {
withdraw(5000,7000);
} catch(Exception e) {
[Link]([Link]());
}
11
}
}
Assignment 10: Login Validation
class LoginException extends Exception {
LoginException(String msg){ super(msg); }
}
class Assign10 {
static void login(String u,String p) throws LoginException {
if( || )
throw new LoginException("Invalid login");
[Link]("Login successful");
}
public static void main(String[] args) {
try {
login("admin","111");
} catch(Exception e) {
[Link]([Link]());
}
}
}
Assignment 11: ATM Pin Validation
class InvalidPinException extends Exception {
InvalidPinException(String msg){ super(msg); }
}
class Assign11 {
static void checkPin(int pin) throws InvalidPinException {
if(pin != 1234)
throw new InvalidPinException("Invalid PIN");
[Link]("PIN accepted");
}
public static void main(String[] args) {
try {
checkPin(1111);
} catch(Exception e) {
[Link]([Link]());
}
12
}
}
Assignment 12: FileNotFoundException
import [Link].*;
class Assign12 {
public static void main(String[] args) {
try {
FileInputStream f = new FileInputStream("[Link]");
} catch(FileNotFoundException e) {
[Link]("File not found");
}
}
}
Assignment 13: InputMismatchException
import [Link].*;
class Assign13 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try {
int n = [Link]();
} catch(InputMismatchException e) {
[Link]("Invalid input");
}
}
}
Assignment 14: Nested try-catch
class Assign14 {
public static void main(String[] args) {
try {
try {
int a = 10/0;
} catch(ArithmeticException e) {
[Link]("Inner catch");
13
}
} catch(Exception e) {
[Link]("Outer catch");
}
}
}
Assignment 15: Exception Propagation
class Assign15 {
static void m1() { int a = 10/0; }
static void m2() { m1(); }
public static void main(String[] args) {
try {
m2();
} catch(Exception e) {
[Link]("Exception propagated");
}
}
}
13. Real-Time Examples
Example 1: Banking System – Insufficient Balance
class InsufficientBalanceException extends Exception {
InsufficientBalanceException(String msg) {
super(msg);
}
}
class Bank {
static void withdraw(int balance, int amount) throws
InsufficientBalanceException {
if (amount > balance)
throw new InsufficientBalanceException("Insufficient Balance");
[Link]("Withdrawal Successful");
}
public static void main(String[] args) {
try {
withdraw(5000, 8000);
14
} catch (Exception e) {
[Link]([Link]());
}
}
}
Example 2: Login Validation
class LoginException extends Exception {
LoginException(String msg) {
super(msg);
}
}
class Login {
static void validate(String user, String pass) throws LoginException {
if ( || )
throw new LoginException("Invalid Login Credentials");
[Link]("Login Successful");
}
public static void main(String[] args) {
try {
validate("admin", "1111");
} catch (Exception e) {
[Link]([Link]());
}
}
}
Example 3: ATM Pin Validation
class InvalidPinException extends Exception {
InvalidPinException(String msg) {
super(msg);
}
}
class ATM {
static void checkPin(int pin) throws InvalidPinException {
if (pin != 1234)
throw new InvalidPinException("Invalid ATM Pin");
[Link]("Pin Accepted");
15
}
}
Example 4: Student Marks Validation
class InvalidMarksException extends Exception {
InvalidMarksException(String msg) {
super(msg);
}
}
class Student {
static void validateMarks(int marks) throws InvalidMarksException {
if (marks < 0 || marks > 100)
throw new InvalidMarksException("Invalid Marks Entered");
[Link]("Marks Accepted");
}
}
14. MCQs (Multiple Choice Questions)
1. Which class is the parent of all exceptions? a) Error b) Exception c) Throwable d) RuntimeException
Ans: c
2. Which block always executes? a) try b) catch c) finally d) throw Ans: c
3. Which keyword is used to explicitly throw exception? a) throws b) throw c) try d) catch Ans: b
4. Checked exceptions are checked at? a) Runtime b) Compile time c) Execution time d) JVM Ans: b
5. Which is unchecked exception? a) IOException b) SQLException c) NullPointerException d)
FileNotFoundException Ans: c
15. Viva Questions (Short Answers)
1. What is an exception?
2. Difference between error and exception?
3. What is default exception handler?
4. Difference between throw and throws?
5. What is checked exception?
6. What is unchecked exception?
7. Can we write try without catch?
16
8. Can finally block be skipped?
9. Why custom exceptions are used?
10. Explain exception propagation.
17