0% found this document useful (0 votes)
4 views10 pages

ExceptionHandling Java Notes InterviewQA

Uploaded by

pallusg2004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

ExceptionHandling Java Notes InterviewQA

Uploaded by

pallusg2004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Exception Handling in Java

Complete Study Notes & Interview Questions


Tap Academy C2C Internship Program — Advanced Java | 2026

1. Context & Revision — Java Execution Pipeline


Before diving into exceptions, recall how a Java program actually runs:

Phase What Happens


Write (.java) You write Java High Level code in a .java file.
Compile (javac) Java Compiler converts .java → Byte Code (.class file).
Compile Time Everything the compiler checks: syntax, types, spelling. Errors here =
Compilation Errors / Syntax Errors.
JVM Loads .class JVM receives byte code and converts it to Machine Level (binary).
Runtime / Execution Processor executes instructions. Problems here = EXCEPTIONS.

Key distinction: Syntax errors are caught at Compile Time. Exceptions occur at Runtime — when the
program is already running.

2. What is an Exception?
2.1 Definition
You have seen pop-ups like:
• "Instagram is not responding. Close the app or wait."
• "WhatsApp has stopped."
• "Chrome is not responding."

All of these are caused by an EXCEPTION inside the application.

Exception (in English) = something UNUSUAL, not ordinary. In Java: an unusual event that disrupts
normal program flow at runtime.

Official Definition: An exception is an unusual event which occurs during the RUNTIME of a Java
program, caused by faulty or unexpected input from the user, which leads to ABRUPT TERMINATION
of the program.

• Exception is a RUNTIME problem — not a compile-time problem


• It occurs because of faulty/unexpected input from the user
• If unhandled → abrupt (sudden, unexpected) termination of the software
• Abrupt termination = worst user experience → users uninstall your app
• Solution: HANDLE the exception gracefully using try-catch

⚠ Abrupt termination is ALWAYS bad for software. A crashing app loses users and revenue.
Exception handling is mandatory for production software.

2.2 Exception vs Compilation Error


Property Compilation Error (Syntax Error) Exception (Runtime Error)
When? During compilation (compile time) During execution (runtime)
Detected by? Java Compiler (javac) JVM
Visible as? Red underline in IDE, compile fails Program crashes with error message
Example Missing semicolon, wrong spelling Dividing by zero, wrong input type
Fixable how? Fix the code syntax Handle with try-catch

2.3 Common Java Exceptions You Must Know


Exception Name When It Occurs
ArithmeticException Division by zero (e.g. 100 / 0). Any invalid arithmetic operation.
InputMismatchException User enters wrong data type (e.g. user enters 'abc' when int is
expected).
NegativeArraySizeExcep Array is created with a negative size (e.g. new int[-5]).
tion
ArrayIndexOutOfBoundsE Accessing an array index that does not exist (e.g. arr[10] when size
xception is 5).
NullPointerException Trying to use an object reference that points to null (object has been
garbage collected or was never created).
NumberFormatException Trying to convert a non-numeric string to a number (e.g.
[Link]('abc')).
StackOverflowError Infinite recursion fills the call stack completely.
ClassCastException Trying to cast an object to a type it doesn't belong to.

3. How Java Handles Exceptions Internally (Memory


Perspective)
3.1 The Flow Without try-catch (Unhandled Exception)
1. Program is running normally inside the main method (stack frame created)
2. A risky line executes — e.g., user divides 100 by 0
3. JVM detects the problem and automatically creates an EXCEPTION OBJECT in memory
4. The exception object contains: (a) What exception? (b) Where did it occur? (c) Why did it occur?
5. The exception object is THROWN to the Runtime System (RTS) — a JRE software
6. RTS checks the method for try-catch. None found → throws to Default Exception Handler
7. Default Exception Handler prints the error on console and ABRUPTLY TERMINATES the
program

The exception object is automatically created by the JVM — you don't create it manually. Example:
ArithmeticException is a class in [Link] package. JVM creates its object automatically when divide-
by-zero occurs.

3.2 The Flow WITH try-catch (Handled Exception)


8. Same steps 1–5 above: exception object is created and thrown to RTS
9. RTS checks the method for try-catch → FOUND!
10. Exception object is thrown directly to the catch block
11. catch block's reference variable (e.g. 'e') holds the reference to the exception object
12. catch block executes — you print a friendly message, log the error, etc.
13. Program CONTINUES normally after the try-catch block — NO abrupt termination

✔ With try-catch: the exception is handled, program continues. Without try-catch: Default Exception
Handler crashes the program.

4. Exception Handling — Syntax & Patterns


4.1 Three Steps to Handle Any Exception
14. IDENTIFY risky code — lines that might throw an exception at runtime
15. PLACE risky code inside a try block
16. WRITE a catch block to handle the exception gracefully

Analogy: Shopping trial room. You TRY the clothes before buying (risky decision). After trying, you
CATCH the result — either buy or leave. Same idea: put risky code in try, decide what to do in catch.

4.2 Pattern 1: Single try — Single catch


try {
// Risky code — any line that might throw an exception
int result = a / b; // risky if b == 0
} catch (Exception e) {
// Handle the exception — print a message, log, redirect
[Link]("Please enter non-zero denominator");
}
• Use when you have one type of exception or want a generic handler
• 'e' is a reference variable pointing to the exception object
• Type 'Exception' is the parent of all exceptions — catches any exception

4.3 Pattern 2: Single try — Multiple catch blocks


try {
// Risky code
} catch (NegativeArraySizeException a) {
[Link]("Invalid size of array");
} catch (InputMismatchException b) {
[Link]("Please enter correct input type");
} catch (ArrayIndexOutOfBoundsException c) {
[Link]("Index is out of bounds");
} catch (Exception d) { // MUST be LAST
[Link]("Some technical problem occurred");
}

• Use when different exceptions need different messages/handling


• SPECIFIC exceptions (child classes) must come FIRST
• GENERAL exception (parent class) must come LAST

⚠ RULE: General/parent exception catch block must ALWAYS be the LAST catch block. If placed first,
it catches ALL exceptions — specific catch blocks below become unreachable code and will never
execute.

4.4 Why General catch Must Be Last — The Unreachable Code Problem
If Exception (general) is placed FIRST:
} catch (Exception d) { // placed first — WRONG!
// This catches EVERYTHING
} catch (NegativeArraySizeException a) { // NEVER reached
} catch (InputMismatchException b) { // NEVER reached

• Every exception object is-a Exception (parent class)


• So the general catch catches ALL exceptions first
• Specific catch blocks below NEVER get a chance to execute
• These become UNREACHABLE CODE — a compile-time warning in Java

Bahubali analogy: In a battle, weak soldiers go first, strongest (Kattappa) goes last as the final
defence. Similarly: specific catches first, general (strongest) catch last.

4.5 Identifying Risky Lines — What Goes Inside try?


• Scanner object creation → risky (file/stream issues)
• nextInt(), nextLine() calls → risky (InputMismatchException if wrong type given)
• Division operations → risky (ArithmeticException if denominator = 0)
• Array creation with user-provided size → risky (NegativeArraySizeException)
• Array access with user-provided index → risky (ArrayIndexOutOfBoundsException)
• Any object usage after setting to null → risky (NullPointerException)
• Print statements using data from risky operations → also risky

✔ Rule of thumb: Any line that depends on user input or external data is a risky line. Put everything
from first user input to final print inside try.

5. Complete Code Examples


5.1 Example 1 — Division with Exception Handling
import [Link];
public class DivisionExample {
public static void main(String[] args) {
[Link]("Connection established");
Scanner scan = new Scanner([Link]);
try {
[Link]("Enter the first number:");
int a = [Link]();
[Link]("Enter the second number:");
int b = [Link]();
int c = a / b;
[Link]("Result: " + c);
} catch (ArithmeticException e) {
[Link]("Please enter non-zero denominator");
} catch (InputMismatchException e) {
[Link]("Please enter integers only");
} catch (Exception e) {
[Link]("Unexpected error occurred");
}
[Link]("Connection terminated");
}
}

5.2 Example 2 — Array with Multiple Exception Handling


import [Link];
public class ArrayExample {
public static void main(String[] args) {
[Link]("Connection established");
Scanner scan = new Scanner([Link]);
try {
[Link]("Enter size of array:");
int size = [Link]();
int[] ar = new int[size];
[Link]("Enter data:");
int data = [Link]();
[Link]("Enter index:");
int index = [Link]();
ar[index] = data;
[Link]("Your data: " + ar[index]);
} catch (NegativeArraySizeException a) {
[Link]("Invalid size: array size cannot be negative");
} catch (InputMismatchException b) {
[Link]("Input type mismatch: please enter integers");
} catch (ArrayIndexOutOfBoundsException c) {
[Link]("Index out of bounds: check your index");
} catch (Exception d) {
[Link]("Some technical problem occurred");
}
[Link]("Connection terminated");
}
}

6. Exception Class Hierarchy — Important for


Interviews
All exceptions in Java are classes. They follow an inheritance hierarchy. Understanding this hierarchy
explains why general catch must be last.

• [Link] ← root of all errors and exceptions in Java


◦ [Link] ← serious system-level problems, NOT handled by developers
◦ └── StackOverflowError, OutOfMemoryError
◦ [Link] ← all catchable exceptions
◦ └── RuntimeException ← unchecked exceptions (occur at runtime)
◦ └── ArithmeticException
◦ └── NullPointerException
◦ └── ArrayIndexOutOfBoundsException
◦ └── NegativeArraySizeException
◦ └── InputMismatchException
◦ └── IOException ← checked exceptions (must be declared/handled)
◦ └── FileNotFoundException

6.1 Checked vs Unchecked Exceptions


Property Checked Exception Unchecked Exception
Also called Compile-time exception Runtime exception
When detected? At compile time (compiler forces At runtime
handling)
Must handle? YES — compiler forces you to handle Not forced, but good practice
or declare
Parent class Exception (non-RuntimeException RuntimeException
Property Checked Exception Unchecked Exception
subclasses)
Examples IOException, FileNotFoundException, ArithmeticException,
SQLException NullPointerException,
ArrayIndexOutOfBoundsException

7. Exception Handling Keywords & Summary


Keyword Purpose & Explanation
try Block that contains risky/suspicious code. If any exception occurs here, it is
thrown to RTS.
catch Block that catches the exception object thrown by the try block. Each catch
handles one type.
finally (Tomorrow's topic) Block that ALWAYS executes — whether exception occurred
or not. Used for cleanup.
throw (Tomorrow's topic) Manually create and throw an exception object. 'Rethrowing'.
throws (Tomorrow's topic) Declare that a method might throw an exception — 'ducking'.
Used in method signature.

7.1 Ways to Handle Exceptions (All Three Methods)


17. try-catch blocks ← Today's topic
18. throw / Rethrowing an exception ← Tomorrow's topic
19. throws / Ducking an exception ← Tomorrow's topic

8. Interview Questions & Answers


8.1 Conceptual Questions
Q: What is an Exception in Java?
A: An exception is an unusual event that occurs during the runtime of a Java program, caused by faulty
or unexpected input from the user, which leads to abrupt termination of the program. Examples:
dividing by zero causes ArithmeticException, entering a string when an integer is expected causes
InputMismatchException.
Q: What is the difference between an Exception and a Syntax Error?
A: A syntax error (compilation error) is detected by the Java compiler during compile time — e.g.,
missing semicolon, wrong spelling of a keyword. An exception is a runtime problem detected by the
JVM during execution — e.g., dividing by zero, accessing an invalid array index. Syntax errors prevent
the program from compiling; exceptions occur when the program is already running.
Q: What happens internally when an exception occurs?
A: When an exception occurs at runtime: (1) JVM automatically creates an exception object containing
what exception, where it occurred, and why. (2) The object is thrown to the Runtime System (RTS). (3)
RTS checks if the method has a try-catch block. (4) If try-catch is present, the object is thrown to the
catch block. (5) If no try-catch, the object goes to the Default Exception Handler which prints the error
and abruptly terminates the program.
Q: What is abrupt termination? Why is it bad?
A: Abrupt termination means the program crashes suddenly and unexpectedly without giving the user a
proper message or cleanup. It is bad because: users lose unsaved work, resources (files, connections)
may not be released properly, users lose trust in the software and may uninstall it, and it can cause
data corruption. Exception handling prevents abrupt termination.
Q: What is the Default Exception Handler in Java?
A: The Default Exception Handler is a built-in JRE software that handles exceptions when no try-catch
block is present. When it receives the exception object, it prints the exception type, message, and stack
trace on the console, then abruptly terminates the program. As developers, we handle exceptions
ourselves to prevent this from happening.

8.2 try-catch Questions


Q: What is a try block? What is a catch block?
A: A try block contains risky code — any code that might throw an exception at runtime. If an exception
occurs inside try, the exception object is thrown to the corresponding catch block. A catch block
receives the exception object through a reference variable and handles it gracefully — printing a
message, logging, or taking corrective action. Together they prevent abrupt termination.
Q: Can we have multiple catch blocks for one try block?
A: Yes. A single try block can have multiple catch blocks. This is used when different exceptions need
different handling. Each catch block handles one specific exception type. RULE: specific exceptions
(child classes like ArithmeticException, NullPointerException) must come first, and the general
exception (parent class Exception) must always be the last catch block.
Q: Why must the general Exception catch block always be last?
A: Because Exception is the parent class of all exceptions. If it is placed first, it catches ALL exceptions
— specific catch blocks below it never get a chance to execute (unreachable code). By placing it last,
we ensure that specific exceptions are handled by their dedicated catch blocks first, and only truly
unexpected exceptions fall through to the general handler.
Q: Can we have a try block without a catch block?
A: Yes, but only if a finally block is present. A try block must be followed by either a catch block, a
finally block, or both. A try block alone with nothing after it is a compilation error.
Q: What is the variable 'e' in catch(Exception e)?
A: 'e' is a reference variable that points to the exception object automatically created by the JVM. It
holds all information about the exception — what happened, where, and why. You can call
[Link]() to get the exception message, [Link]() for the full stack trace. The name 'e'
is just a convention — you can use any valid identifier.

8.3 Exception-Specific Questions


Q: What is ArithmeticException? When does it occur?
A: ArithmeticException occurs when an invalid arithmetic operation is performed at runtime. The most
common cause is dividing an integer by zero (e.g., int c = a / b when b = 0). In mathematics, dividing by
zero is undefined — Java throws ArithmeticException to signal this invalid operation. Note: floating-
point division by zero gives Infinity, not an exception.
Q: What is NullPointerException? When does it occur?
A: NullPointerException (NPE) occurs when you try to use an object reference that points to null —
meaning the object does not exist in memory. This happens when: (1) you set an object to null and then
try to use it, (2) you never initialized an object but try to call methods on it. NPE is one of the most
common exceptions in Java production code.
Q: What is ArrayIndexOutOfBoundsException?
A: This exception occurs when you try to access an array index that is outside the valid range. For an
array of size n, valid indices are 0 to n-1. Accessing index -1 or index n or beyond causes
ArrayIndexOutOfBoundsException. This is a RuntimeException — it cannot be detected at compile time
because the index value may depend on user input.
Q: What is NegativeArraySizeException?
A: This exception occurs when you try to create an array with a negative size. For example: int[] arr =
new int[-5]. Array size must be zero or positive. Zero is allowed — it creates an array with no elements.
Negative is not allowed — JVM throws NegativeArraySizeException.
Q: What is InputMismatchException?
A: This exception from [Link] package occurs when the Scanner's nextInt() (or similar method)
receives input that doesn't match the expected data type. For example, if the program calls nextInt()
and the user types 'hello', a string cannot be parsed as an integer — InputMismatchException is
thrown.

8.4 Hierarchy & Design Questions


Q: What is the parent class of all exceptions in Java?
A: The root of all exceptions and errors in Java is [Link]. It has two direct subclasses: (1)
Error — for serious system-level problems like StackOverflowError and OutOfMemoryError, which
developers don't handle. (2) Exception — for all catchable exceptions that developers should handle.
Q: What is the difference between Error and Exception in Java?
A: Both extend Throwable. Error represents serious JVM-level problems (StackOverflowError,
OutOfMemoryError) that are generally unrecoverable — developers don't handle these. Exception
represents application-level problems that can and should be handled by developers using try-catch.
RuntimeException is a subclass of Exception for unchecked exceptions.
Q: What is the difference between checked and unchecked exceptions?
A: Checked exceptions are detected at compile time — the compiler forces you to handle them (try-
catch) or declare them (throws). Examples: IOException, FileNotFoundException, SQLException.
Unchecked exceptions (RuntimeException subclasses) are not detected at compile time — they occur
during runtime and are not forced by the compiler. Examples: ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException.
Q: Can we write catch before try?
A: No. The syntax in Java strictly requires try to come first, followed by one or more catch blocks,
optionally followed by a finally block. Writing catch before try is a syntax error and the program will not
compile.
Q: What real-world example demonstrates exception handling?
A: BookMyShow (ticket booking app) is a great example. When you enter an incorrect UPI PIN, the app
doesn't crash — it shows 'Incorrect UPI PIN, please try again.' The failed payment is an exception
(ArithmeticException-level problem in the payment system), but BookMyShow handles it gracefully with
a user-friendly message and lets you retry. If exception handling wasn't done, the app would crash
completely. This is exactly what try-catch achieves in code.

9. Quick Reference Cheat Sheet


Term One-Line Definition
Exception Unusual event at RUNTIME that abruptly terminates the program.
Syntax Error Problem at COMPILE TIME — wrong grammar, missing semicolon.
Runtime Execution phase — when the JVM is actually running the program.
Exception Object Object created by JVM when exception occurs. Contains what, where,
why.
RTS (Runtime System) JRE software that receives exception object and checks for try-catch.
Default Exception Handler JRE software that prints error and crashes program if no try-catch
found.
try block Block containing risky code. Exception from here goes to catch.
catch block Block that receives and handles the exception object.
finally block Block that ALWAYS runs — exception or not. (Upcoming topic)
throw Manually throw an exception object. (Upcoming topic)
throws Declare a method may throw an exception. (Upcoming topic)
ArithmeticException Division by zero or invalid math operation.
NullPointerException Using an object reference that is null.
ArrayIndexOutOfBoundsE Accessing array index outside 0 to n-1.
xception
NegativeArraySizeExcepti Creating array with negative size.
on
InputMismatchException User gives wrong data type (string instead of int).
Checked Exception Compiler forces handling. E.g. IOException.
Unchecked Exception Compiler doesn't force handling. E.g. ArithmeticException.
Abrupt Termination Program crashes suddenly — BAD. Exception handling prevents this.
Normal Termination Program finishes properly — GOOD. try-catch ensures this.

Handle every exception. Never let your software crash. That is your responsibility as a
developer.
Next class: throw, throws, finally, rethrowing & ducking exceptions. — Tap Academy 2026

You might also like