0% found this document useful (0 votes)
5 views24 pages

Java Exception Handling Explained

The document provides an overview of Java Exception Handling, detailing the types of errors (compile-time and runtime) and the concept of exceptions as unexpected events disrupting program flow. It explains the mechanism of exception handling using try, catch, and finally blocks, along with the distinction between checked and unchecked exceptions. Additionally, it covers the use of the throw and throws keywords for managing exceptions in Java programs.
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)
5 views24 pages

Java Exception Handling Explained

The document provides an overview of Java Exception Handling, detailing the types of errors (compile-time and runtime) and the concept of exceptions as unexpected events disrupting program flow. It explains the mechanism of exception handling using try, catch, and finally blocks, along with the distinction between checked and unchecked exceptions. Additionally, it covers the use of the throw and throws keywords for managing exceptions in Java programs.
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

Java Exception Handling

Before Starting: What is an Error?

An error is a serious problem that occurs either at compile-time or


runtime and usually cannot be recovered by the program.

Types of Errors:

1. Compile-time Error:

 Occurs during compilation due to wrong syntax or misuse of language rules.


 Example: missing semicolon, wrong variable declaration.
 We cannot handle these errors in Java.

2. Runtime Error:

 Occurs while the program is running, even if compilation was successful.


 Example: divide by zero, invalid array index.
 These are handled using Exception Handling.

Exception:

 An Exception is an unexpected event that occurs during program execution and


disrupts the normal flow of instructions.
 There are runtime errors.
 If exception occurs immediately the program will be terminated abnormally.
 In java exceptions are objects of exception class.

Exception Handling:

 Exception Handling is a mechanism in Java to handle runtime errors so that the


program can continue its normal execution without crashing.
 Simply providing an alternative way when exception raised.

Realtime example:

Imagine you are going to college or office.

 You started on time.


 Everything was going smoothly.
 Suddenly something unexpected happens…

It starts raining heavily

 You cannot drive for a while.


 You stop and wait until the rain stops.
 Then you continue your journey safely.

P a g e 1 | 24
This is exactly like an Exception in Java.

 Rain = Unexpected event (Exception)


 Waiting until it stops = Handling the Exception (try-catch)
 Continuing after rain = Normal flow resumes

Why exceptions are occurred:


In a program, not all statements are the same.
Some statements are always safe, while others are risky and may fail unexpectedly.

We can divide statements into two categories:

1. Normal Statements (Safe Statements)


 These are safe statements.
 They execute normally and never raise exceptions.
 The output is always predictable.

Example:

int a = 10 + 20 + 60; // always works fine

[Link](a); // safe

2. Risky (Dangerous) Statements:


 These statements are uncertain.
 Sometimes they work fine, but sometimes they may throw exceptions.
 We cannot predict their behavior at compile-time.
 If exception occurs → program stops abnormally.

Example code:

int a = 10 / 0; // risky statement

int[] arr = new int[-9]; //risky code

For every thread JVM will create a separate stack at the time of Thread
creation. All method calls performed by that thread will be stored in that
stack. Each entry in the stack is called "Activation record" (or) "stack
frame". After completing every method call JVM removes the
corresponding entry from the stack. After completing all method calls JVM
destroys the empty stack and terminates the program normally.

P a g e 2 | 24
Example:

How the program flow in stack memory for example 1

In example 2 program flow will be same but program terminates


abnormally.

Default Exception Handling in Java:


1. If an exception raised inside any method then that method is
responsible to create Exception object with the following information.

1. Name of the exception.

2. Description of the exception.

3. Location of the exception. (StackTrace)

2. After creating that Exception object, the method handovers that object
to the JVM.

3. JVM checks whether the method contains any exception handling code
or not. If method won't contain any handling code then JVM terminates
that method abnormally and removes corresponding entry form the stack.

P a g e 3 | 24
4. JVM identifies the caller method and checks whether the caller method
contain any handling code or not. If the caller method also does not
contain handling code then JVM terminates that caller method also
abnormally and removes corresponding entry from the stack.

5. This process will be continued until main() method and if the main()
method also doesn't contain any exception handling code then JVM
terminates main() method also and removes corresponding entry from the
stack.

6. Then JVM handovers the responsibility of exception handling to the


default exception handler.

7. Default exception handler just print exception information to the


console in the following format and terminates the program abnormally.

Exception in thread “xxx(main)” Name of exception: description


Location of exception (stack trace)

How to handle the exceptions:


When an exception occurs, if we don’t handle it, the program will stop
abnormally.
To prevent program crash, Java provides Exception Handling.

We handle exceptions using three important blocks:

1. try block:
Purpose

 Enclose statements that might throw exceptions.

 The JVM monitors this block; if an exception is thrown, control


jumps out to a matching catch (or propagates after finally).

Rules

 A traditional try must be followed by at least one catch or a


finally (or both).

 A try-with-resources (Java 7+) can appear without catch and


finally; resources still close automatically, and any exception
propagates.

 Only risky code should go inside; keep it minimal so you don’t


hide bugs.

P a g e 4 | 24
Control flow

 If no exception: execute the whole try, skip catch blocks, then run
finally (if present).

 If exception occurs: stop the try at the throwing statement → jump


to the first compatible catch → run finally.

2. catch block:
Purpose

 Handle a specific type (or family) of exceptions thrown in the


associated try.

Matching & ordering

 The first catch whose parameter type matches (same type or


superclass) will handle it.

 Order matters: put more specific exceptions before more general


ones.
Placing Exception or Throwable first makes later specific catches
unreachable → compile error.

Example:

try {
[Link]( 10 / 0);
} catch (ArithematicException e) {
[Link](10 / 4);
}

Try with multiple catch blocks:


 A try block can be followed by multiple catch blocks.
 This allows us to handle different exception types separately.
 At runtime, only the matching catch block will execute.
 If no catch matches, the program terminates abnormally (unless
there’s a higher-level handler).

Note: Recommended way is use multiple catch for multiple don’t use
Exception for every exception

Syntax:

P a g e 5 | 24
Example: for try with multiple catch

Multi-Catch Block in Java:

 A multi-catch block allows a single catch block to handle multiple


exception types.

 Introduced in Java 7 to reduce code duplication when different


exceptions have the same handling logic.

 The exceptions must not have an inheritance relationship (e.g.,


IOException | FileNotFoundException is NOT allowed because
FileNotFoundException is a subclass of IOException).

P a g e 6 | 24
Example:

1. Multi-catch is used only when same handling logic applies.

2. Inside a multi-catch, the exception object (e) is implicitly final.

o You cannot reassign it:

o e = new Exception(); // Compile-time error

3. Order still matters → multi-catch must come before a general


Exception block.

[Link] block:
 Runs no matter what (normal completion, handled exception, or
unhandled exception).
 Ideal for cleanup: closing files/streams/sockets, releasing locks,
resetting temporary state.
 It is generally used to place cleanup code (closing files, releasing
resources, closing DB connections, etc.).
P a g e 7 | 24
we can use finally without catch block also but if exception raised then
finally executed after print the exception trace.
even if return statement is present un try block : after execution of finally
block and return statement executes.

P a g e 8 | 24
P a g e 9 | 24
Exception hierarchy:

P a g e 10 | 24
Types of Exceptions in Java:
[Link] Exceptions (Compile-time exceptions)
 These are exceptions that are checked by the compiler at
compile time.

 If you don’t handle them (using try-catch or throws), your program


won’t compile.

 They usually occur due to external resources like files, DB, or


network.

Examples:

 OutOfMemoryError
 StackOverflowError
 VirtualMachineError
Why Checked Exceptions exist?

1. All exceptions occur at runtime only (there is no such thing as


"compile time exception happening").

2. But for Checked Exceptions, the compiler predicts that this line
of code may throw an exception when executed.

3. So, compiler forces you to either:

o Handle it with try–catch, OR

o Declare it using throws in method signature.

4. If you don’t, the program won’t compile.

[Link] Exceptions (Runtime exceptions)


 These occur while the program is running, not at compile time.

 Compiler doesn’t force you to handle them.

 Usually caused by programming mistakes like wrong logic, invalid


input, or null values.

 Compiler wont aware about this exceptions.

Examples:

 NullPointerException
 ArithmeticException (divide by zero)
 ArrayIndexOutOfBoundsException
 NumberFormatException

P a g e 11 | 24
3. Errors (Not Exceptions, but part of Throwable)
 These are serious problems that cannot be recovered by normal
program.

 They occur due to system-level issues (memory shortage, JVM


crash).

 Not meant to be handled by programmer.

Examples:

 OutOfMemoryError

 StackOverflowError

 VirtualMachineError

Example:

public class SimpleExceptionHandling {


public static void main(String[] args) {
[Link]("Program Started...");

try {
int num1 = 20;
int num2 = 0; // risky value
int result = num1 / num2; // risky code
[Link]("Result: " + result);
}
catch (ArithmeticException e) {
[Link]("Exception Handled ");
}

[Link]("Program Ended...");
}
}

P a g e 12 | 24
Flow of Execution:

1. Program Started... is printed.

2. Risky code → 20 / 0 → ArithmeticException.

3. JVM looks for matching catch.

4. catch (ArithmeticException e) found → executes


[Link]("Exception Handled...").

5. After catch block → continues normal flow → prints Program Ended....

Program ends normally.

If we did not use that try catch then

1. Program Started... is printed.

2. Risky code → 20 / 0 → JVM throws ArithmeticException.

3. No try-catch present → JVM terminates program abnormally.

4. Program Ended... is not printed.

Program ends abnormally.

Various methods to print exception information:


Throwable class defines the following methods to print exception
information to the console.

1. printStackTrace()
 Definition: Prints the name of the exception, description, and
stack trace (line numbers where exception occurred).

 Use case: Best for debugging, since it shows the exact line of error.

 Output format:

ExceptionName: Description

at [Link](FileName:LineNumber)

at ...

P a g e 13 | 24
Example:

public class PrintStackTraceEx {


public static void main(String[] args) {
try {
int a = 10 / 0; // risky
} catch (ArithmeticException e) {
[Link](); // full details
}
}
}

Output:

[Link]: / by zero

at [Link]([Link])

2. toString()
 Definition: Returns a string representation of the exception.

 Output: Contains only the exception name + description.

 Does not show stack trace. (return string )

public class ToStringEx {


public static void main(String[] args) {
try {
String s = null;
[Link]([Link]());
} catch (NullPointerException e) {
[Link]([Link]());
}
}
}

Output:

P a g e 14 | 24
[Link]: Cannot invoke "[Link]()" because
"s" is null

3. getMessage()
 Definition: Returns only the detailed message (description) of
the exception.

 Does not show class name or stack trace.

 Use case: When you want to display a user-friendly message.

Example:

public class GetMessageEx {


public static void main(String[] args) {
try {
int arr[] = new int[3];
[Link](arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]([Link]());
}
}
}

Output”:

Index 5 out of bounds for length 3

Summery table:
Method Output Format Example Output

printStackTrac Exception Name [Link]: / by


e() + Description + zero at ...
Stack Trace

toString() Exception Name [Link]:


+ Description Cannot invoke "[Link]()"
because "s" is null

getMessage() Only Description Index 5 out of bounds for length 3

P a g e 15 | 24
throw keyword:
 The throw keyword in Java is used to explicitly throw an exception
from a method or block of code.

 Only one exception object can be thrown at a time.

 We can throw both checked and unchecked exceptions.

 Sometimes we can create Exception object explicitly and we can


hand over to the JVM manually by using throw keyword.

Note:

In general, we can use throw keyword for customized exceptions


(user defined exceptions) but not for predefined exceptions.
Syntax:

 We can throw only objects of Throwable class or its subclasses


(Exception or Error).
 throw is used inside a method or block.
 After throw statement, no other code will execute in that block.
 Used to create custom error situations.

Example:

public class Testing {


public static void main(String[] args) {
for(int i = 0; i<=10; i++) {
if(i==5) {
throw new ArithmeticException("exception
raised manually");
}
}
}
}

P a g e 16 | 24
We can use throw keyword only for Throwable types otherwise we will get
compile time error saying incomputable types.

public class Testing {


public static void main(String[] args) {
for(int i = 0; i<=10; i++) {
if(i==5) {
throw new Testing();
}
}
}
}

Output: compile time error : incompatible types ……..

Throws ketword:
 The throws keyword is used in a method declaration to indicate that
the method may throw one or more exceptions during execution.

 It is mainly used for checked exceptions (like IOException,


SQLException), because the compiler forces us to handle or declare
them.

 It passes the responsibility of handling the exception to the caller of


the method.

 In our program if there is any chance of raising checked exception


then compulsory we should handle either by try catch or by throws
keyword otherwise the code won't compile.

 We can use throws keyword to delegate the responsibility of


exception handling to the caller method. Then caller method is
responsible to handle that exception. This process is called
exception propagation.

 "throws" keyword required only to convince complier. Usage of


throws keyword doesn't prevent abnormal termination of the
program. Hence recommended to use try-catch over throws
keyword.

Key Points
P a g e 17 | 24
1. throws informs the caller of the method that this method might
throw an exception.

2. It allows exception handling to be delegated to the calling method.

3. You can declare multiple exceptions separated by commas.

4. Only checked exceptions must be declared; unchecked (like


ArithmeticException) are optional.

Example 1: Single Exception


import [Link];
public class ThrowsExample {
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
[Link]([Link]());
}
}

public static void readFile() throws IOException {


throw new IOException("File not found!");
}
}

output: File not found!

Example 2: Multiple Exceptions


import [Link];
import [Link];
public class MultipleThrowsCheck {
public static void main(String[] args) {
try {
riskyMethod();
} catch (IOException e) {

P a g e 18 | 24
[Link](e);
} catch (SQLException e){
[Link](e);
}
}

static void riskyMethod() throws IOException, SQLException


{
int option = 1;
if (option == 1) {
throw new IOException("IO Problem occurred");
} else {
throw new SQLException("SQL Problem occurred");
}
}
}

Output: [Link]: IO problem occurred.

Difference between throw and throws:

throw throws

Used to explicitly throw an Used in method declaration to


exception inside a method/block. specify which exceptions the method
may throw.

Only one exception can be Multiple exceptions can be declared,


thrown at a time. separated by commas.

Followed by an exception Followed by one or more exception


object. class names.

Example: throw new Example: void m() throws


IOException("error"); IOException, SQLException

P a g e 19 | 24
Example:

public class Test {


public static void m1() throws FileNotFoundException {
throw new FileNotFoundException();
}
public static void main(String[] args) {
try {
m1();
} catch (FileNotFoundException e) {
[Link]();
}
}
}

Note:

1. we can use throws keyword only for Throwable types otherwise we will
get compile time error saying incompatible types.

public class Test {


public static void m1() throws Animal {
throw new FileNotFoundException();
}
public static void main(String[] args) {
try {
m1();
} catch (FileNotFoundException e) {
[Link]();
}
}
}
Above example we will get CE error because Animal is not throwable
means (it is not child class of any exception , runtimeException, throwable
class).

2. We can use throws keyword only for constructors and methods but not
for classes.

Ex:

P a g e 20 | 24
User defined Exceptions:
 Java has many built-in exceptions (like ArithmeticException,
ArrayIndexOutOfBoundsException, etc.).
 But sometimes, in real projects, we need our own exception
type to represent a specific business error.

For this we create user-defined exceptions by extending Exception


(checked) or RuntimeException (unchecked).

 Sometimes we can create our own exception to meet our


programming requirements. Such type of exceptions are called
customized exceptions (user defined exceptions).

 Steps to create user defined exception:

 Create a class that extends Exception (checked) or


RuntimeException (unchecked).

 Create a constructor that accepts a message and passes it to the


superclass using super(message).

 Throw the exception from your custom class using the throw
keyword.

 Handle the exception using a try-catch block.

Example 1: Checked Custom Exception:

// Step 1: Define custom exception


class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}

// Step 2: Use it in a class


public class Bank {
public static void withdraw(int amount) throws
InsufficientFundsException {
int balance = 5000;
P a g e 21 | 24
if(amount > balance) {
// Step 3: Throw exception
throw new InsufficientFundsException("Not enough
balance! Available: " + balance);
}
else {
[Link]("Withdrawal successful.
Remaining balance: " + (balance - amount));
}
}

public static void main(String[] args) {


try {
withdraw(6000); // risky code
}
catch (InsufficientFundsException e) {
// Step 4: Handle exception
[Link]([Link]());
}
}
}

Output: Exception Caught: Not enough balance! Available: 5000

Example 2: Unchecked Custom Exception


// Extending RuntimeException (unchecked)
class AgeInvalidException extends RuntimeException {
public AgeInvalidException(String message) {
super(message);
}

P a g e 22 | 24
}

public class VotingApp {


public static void main(String[] args) {
int age = 15;

if (age < 18) {


throw new AgeInvalidException("Age must be 18 or
above to vote!");
}
else {
[Link]("You are eligible to vote!");
}
}
}

Output:
Exception in thread "main" AgeInvalidException: Age must be 18
or above to vote!

Key Points

 Extend Exception → Checked Exception (must be declared in


throws).

 Extend RuntimeException → Unchecked Exception (no need to


declare in throws).

 Always give meaningful exception class names like


ProductNotFoundException, InvalidLoginException, etc.

P a g e 23 | 24
Important technical interview questions:
1. What is the difference between Error and Exception in Java?
2. Difference between checked and unchecked exceptions? (with
examples)
3. Difference between throw and throws keywords?
4. Difference between final, finally, and finalize()?
5. Can we have a try block without catch?
6. Can we have a try block without finally?
7. Can finally block be skipped? (return, [Link] cases)
8. Difference between printStackTrace(), getMessage(), and toString()?
9. What happens if an exception occurs in a catch block itself?
10. Can constructors use throws keyword?
11. Can overridden methods throw different exceptions than parent
methods?
12. What is try-with-resources? How is it better than finally?
13. Can we catch multiple exceptions in a single catch block? (Java 7
feature)
14. What is exception chaining in Java? (getCause() / initCause())
15. Why should we avoid catching generic Exception?
16. Why do we need user-defined exceptions if Java has many built-in
ones?
17. What happens if exception is not caught anywhere?
18. What is the difference between Exception and RuntimeException?
19. What is re-throwing an exception?
20. Best practices for exception handling in Java?

P a g e 24 | 24

You might also like