NBKRIST – Java Hub

Java Exception Handling FAQ & Assignment

Expert View

As a software engineer, I believe that real learning begins when students start asking *why*. The FAQ below addresses not just definitions, but also the reasoning behind Java’s design. Understanding these ensures you can handle errors like a professional developer, not just a student.

What is an Exception in Java?

An Exception is an event that disrupts the normal execution flow of a program. Exception handling allows developers to catch and handle such runtime events gracefully, maintaining application stability.

Difference between Checked and Unchecked Exceptions
  • Checked: Verified at compile-time (e.g. IOException).
  • Unchecked: Detected at runtime (e.g. NullPointerException).
// Example
try {
  FileReader fr = new FileReader("file.txt");
} catch(IOException e) {
  System.out.println("Checked exception handled.");
}
      
What are the 5 keywords used in Exception Handling?
  1. try — Monitor risky code
  2. catch — Handle the exception
  3. finally — Execute cleanup code
  4. throw — Manually raise exception
  5. throws — Declare exception propagation
Purpose of try, catch, and finally Blocks
try {
   int num = 10 / 0;
} catch (ArithmeticException e) {
   System.out.println("Division by zero!");
} finally {
   System.out.println("Cleanup code runs here.");
}
      
Difference between throw and throws Keywords
  • throw — Used to raise a specific exception instance.
  • throws — Declares possible exceptions for a method.
void validate(int age) throws Exception {
  if(age < 18)
    throw new Exception("Underage");
}
      
Can a try block exist without catch or finally?

No. A try must be followed by either catch or finally (or both).

When is finally block not executed?
  • When System.exit() is invoked.
  • When JVM crashes or power failure occurs.
Explain Java Exception Hierarchy
Throwable
├── Error
│   ├── OutOfMemoryError
│   └── StackOverflowError
└── Exception
    ├── IOException (Checked)
    ├── SQLException (Checked)
    └── RuntimeException (Unchecked)
      ├── NullPointerException
      ├── ArithmeticException
      └── ArrayIndexOutOfBoundsException
      
How to Create Custom Exceptions?
class InvalidAgeException extends Exception {
  InvalidAgeException(String msg) {
    super(msg);
  }
}
      
Explain Exception Propagation

When an exception is not handled in one method, it propagates to the calling method. This continues until caught or until the JVM terminates the program.

🔑 Key Summary

By mastering these fundamentals, you can confidently handle any exception scenario in professional Java applications.