0% found this document useful (0 votes)
2 views

Exception Handling in Java

Exception Handling in Java is a mechanism to manage runtime errors and maintain the application's normal flow, utilizing concepts like try-catch blocks, throw, throws, and finally blocks. There are two main types of exceptions: checked exceptions, which are verified at compile-time, and unchecked exceptions, which occur at runtime. Best practices for exception handling include using specific exceptions, avoiding empty catch blocks, and ensuring proper resource cleanup.

Uploaded by

Jha Avinash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Exception Handling in Java

Exception Handling in Java is a mechanism to manage runtime errors and maintain the application's normal flow, utilizing concepts like try-catch blocks, throw, throws, and finally blocks. There are two main types of exceptions: checked exceptions, which are verified at compile-time, and unchecked exceptions, which occur at runtime. Best practices for exception handling include using specific exceptions, avoiding empty catch blocks, and ensuring proper resource cleanup.

Uploaded by

Jha Avinash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

‭1. What is Exception Handling in Java?

‭●‬ D ‭ efinition‬‭: Exception Handling in Java is a mechanism‬‭to handle runtime errors,‬


‭ensuring the normal flow of the application.‬
‭●‬ ‭Exceptions‬‭: These are events that disrupt the normal‬‭flow of a program. For‬
‭example, accessing an invalid array index or dividing by zero.‬
‭●‬ ‭Key Concepts‬‭:‬
‭○‬ ‭Try-catch blocks‬‭: To handle exceptions.‬
‭○‬ ‭Throw and Throws‬‭: To explicitly throw exceptions and‬‭declare them.‬
‭○‬ ‭Finally block‬‭: To execute code regardless of whether‬‭an exception occurred.‬

‭2. Types of Exceptions in Java‬

‭(a) Checked Exceptions‬

‭‬ T
● ‭ hese are exceptions checked at compile-time.‬
‭●‬ ‭Examples:‬
‭○‬ ‭
IOException‬
‭○‬ ‭SQLException‬

‭ xample‬‭:‬
E
‭Java code‬
import java.io.*;‬

public class CheckedExceptionExample {‬



public static void main(String[] args) {‬

‭try {‬
‭FileReader file = new FileReader("nonexistent.txt");‬
‭} catch (FileNotFoundException e) {‬
‭System.out.println("File not found: " + e.getMessage());‬
‭}‬
}‬

}‬

‭(b) Unchecked Exceptions‬

‭‬ T
● ‭ hese occur during runtime and are not checked at compile-time.‬
‭●‬ ‭Examples:‬
‭○‬ ‭
ArithmeticException‬
‭○‬N‭ullPointerException‬
‭‬ ‭
○ ArrayIndexOutOfBoundsException‬
‭ xample‬‭:‬
E
‭Java code‬
public class UncheckedExceptionExample {‬

public static void main(String[] args) {‬

‭int num = 10 / 0; // Causes ArithmeticException‬
}‬

}‬

‭(c) Errors‬

‭‬ E
● ‭ rrors are serious issues that the application cannot recover from.‬
‭●‬ ‭Examples:‬
‭○‬ ‭
StackOverflowError‬
‭○‬ ‭OutOfMemoryError‬

‭3. Exception Hierarchy‬

‭Java has a predefined class hierarchy for exceptions:‬

‭●‬ ‭Root‬‭:‬‭
Throwable‬
‭○‬ ‭Error‬‭: Irrecoverable issues (e.g., JVM errors).‬
‭○‬ ‭Exception‬‭: Recoverable conditions:‬
‭■‬ ‭Checked exceptions (‬‭ IOException‬ ‭,‬‭
SQLException‬‭).‬
‭■‬ ‭Unchecked exceptions (‬‭
ArithmeticException‬‭,‬
‭NullPointerException‬‭).‬

‭4. Try-Catch Block‬


‭ yntax‬‭:‬
S
‭Java code‬
try {‬

// Code that may throw an exception‬

} catch (ExceptionType e) {‬

// Code to handle exception‬

}‬

‭ xample‬‭:‬
E
‭Java code‬
public class TryCatchExample {‬

public static void main(String[] args) {‬

‭try {‬
‭int num = 10 / 0;‬
‭} catch (ArithmeticException e) {‬
‭System.out.println("Error: " + e.getMessage());‬
‭}‬
}‬

}‬

‭5. Finally Block‬

‭‬ A
● ‭ lways executes whether an exception occurs or not.‬
‭●‬ ‭Used for cleanup operations like closing files or database connections.‬

‭ xample‬‭:‬
E
‭Java code‬
public class FinallyExample {‬

public static void main(String[] args) {‬

‭try {‬
‭int num = 10 / 0;‬
‭} catch (ArithmeticException e) {‬
‭System.out.println("Caught: " + e.getMessage());‬
‭} finally {‬
‭System.out.println("This block always executes.");‬
‭}‬
}‬

}‬

‭6. Throw and Throws‬

‭(a) Throw‬

‭●‬ ‭Used to explicitly throw an exception.‬

‭ yntax:‬
S
‭Java code‬
throw new ExceptionType("Exception message");‬

‭ xample‬‭:‬
E
‭Java code‬
public class ThrowExample {‬

public static void main(String[] args) {‬

‭validateAge(15);‬
}‬

static void validateAge(int age) {‬

‭if (age < 18) {‬
‭throw new IllegalArgumentException("Age must be 18 or‬
above");‬

‭}‬
‭System.out.println("Valid age");‬
}‬

}‬

‭(b) Throws‬

‭●‬ ‭Used in method signatures to declare exceptions that the method might throw.‬

‭ yntax:‬
S
‭Java code‬
returnType methodName() throws ExceptionType1, ExceptionType2 {‬

// Method code‬

}‬

‭ xample‬‭:‬
E
‭Java code‬
import java.io.*;‬

public class ThrowsExample {‬



public static void main(String[] args) throws IOException {‬

‭FileReader file = new FileReader("nonexistent.txt");‬
}‬

}‬

‭7. Custom Exceptions‬

‭‬ W
● ‭ e can create user-defined exceptions by extending the‬‭
Exception‬‭class.‬
‭●‬ ‭Steps‬‭:‬
‭1.‬ ‭Extend the‬‭ Exception‬‭class (or‬‭
RuntimeException‬‭for‬‭unchecked‬
‭exceptions).‬
‭2.‬ ‭Provide a constructor for custom messages.‬

‭ xample‬‭:‬
E
‭Java code‬
class InvalidAgeException extends Exception {‬

public InvalidAgeException(String message) {‬

‭super(message);‬
}‬

}‬

public class CustomExceptionExample {‬



public static void main(String[] args) {‬

‭try {‬
‭checkAge(15);‬
‭} catch (InvalidAgeException e) {‬
‭System.out.println("Exception: " + e.getMessage());‬
‭}‬
}‬

static void checkAge(int age) throws InvalidAgeException {‬



‭if (age < 18) {‬
‭throw new InvalidAgeException("Age must be 18 or‬
above");‬

‭}‬
‭System.out.println("Valid age");‬
}‬

}‬

‭8. Multiple Catch Blocks‬

‭‬ A
● ‭ ‬‭
try‬‭block can be followed by multiple‬‭
catch‬‭blocks‬‭to handle different exceptions.‬
‭●‬ ‭Rule‬‭: More specific exceptions should come before‬‭more general ones.‬

‭ xample‬‭:‬
E
‭Java code‬
public class MultipleCatchExample {‬

public static void main(String[] args) {‬

‭try {‬
‭int arr[] = new int[5];‬
‭arr[5] = 10 / 0;‬
‭} catch (ArithmeticException e) {‬
‭System.out.println("ArithmeticException caught: " +‬
e.getMessage());‬

‭} catch (ArrayIndexOutOfBoundsException e) {‬
‭System.out.println("ArrayIndexOutOfBoundsException‬
caught: " + e.getMessage());‬

‭}‬
}‬

}‬

‭9. Try-With-Resources (Automatic Resource Management)‬

‭ ‬ I‭ntroduced in‬‭Java 7‬‭, it ensures resources are closed‬‭automatically after use.‬



‭●‬ ‭Works with classes implementing‬‭ AutoCloseable‬‭or‬‭ Closeable‬‭interfaces‬‭.‬

‭ xample‬‭:‬
E
‭Java code‬
import java.io.*;‬

public class TryWithResourcesExample {‬



public static void main(String[] args) {‬

‭try (BufferedReader br = new BufferedReader(new‬
FileReader("test.txt"))) {‬

‭System.out.println(br.readLine());‬
‭} catch (IOException e) {‬
‭System.out.println("IOException: " + e.getMessage());‬
‭}‬
}‬

}‬

‭10. Exception Propagation‬

‭●‬ ‭Exceptions are propagated from one method to another unless handled explicitly.‬

‭ xample‬‭:‬
E
‭Java code‬
public class ExceptionPropagationExample {‬

public static void main(String[] args) {‬

‭try {‬
‭method1();‬
‭} catch (ArithmeticException e) {‬
‭System.out.println("Caught: " + e.getMessage());‬
‭}‬
}‬

static void method1() {‬



‭method2();‬
}‬

static void method2() {‬

‭int num = 10 / 0; // Causes ArithmeticException‬
}‬

}‬

‭11. Best Practices‬

‭1.‬ ‭Always use‬‭specific exceptions‬‭instead of generic‬‭ones like‬‭


Exception‬‭or‬
Throwable‬
‭ ‭.‬
‭ .‬
2 ‭ void swallowing exceptions (empty catch blocks).‬
A
‭3.‬ ‭Use‬‭finally‬‭or try-with-resources for resource cleanup.‬
‭4.‬ ‭Don't overuse custom exceptions; only create them when necessary.‬
‭5.‬ ‭Handle exceptions gracefully to avoid application crashes.‬

‭Common Interview Questions on Exception Handling in Java‬

‭1. What is the difference between‬‭


throw‬‭and‬‭
throws‬‭?‬
‭Aspect‬ ‭throw‬ throws‬

‭Purpose‬ ‭ sed to explicitly throw an‬
U ‭ eclares exceptions that a method‬
D
‭exception.‬ ‭can throw.‬

‭Usage‬ ‭Inside the method body.‬ ‭In the method signature.‬

‭ umber of‬
N ‭ an throw only one exception‬
C ‭ an declare multiple exceptions‬
C
‭Exceptions‬ ‭at a time.‬ ‭separated by commas.‬

‭Example‬ t‭hrow new‬ ‭oid method() throws‬


v
‭Exception("Error");‬ IOException {}‬

‭2. What is the difference between checked and unchecked exceptions?‬


‭Aspect‬ ‭Checked Exceptions‬ ‭Unchecked Exceptions‬

‭Definition‬ ‭ xceptions checked at‬


E ‭Exceptions checked at runtime.‬
‭compile-time.‬

‭Inheritance‬ ‭Subclasses of‬‭


Exception‬
‭,‬ ‭Subclasses of‬
‭excluding‬‭
RuntimeException‬
‭.‬ RuntimeException‬
‭ ‭.‬
‭Examples‬ ‭IOException‬‭,‬‭
SQLException‬ ‭ullPointerException‬‭,‬
N
ArithmeticException‬

‭ andling‬
H ‭Must be handled using‬ ‭ o handling required by the‬
N
‭Requirement‬ ‭try-catch‬‭or declared using‬ ‭compiler.‬
‭throws‬‭.‬

‭3. Can you explain the use of the‬‭


finally‬‭block?‬

‭●‬ T ‭ he‬‭finally‬‭block is used for‬‭cleanup operations‬‭, such as closing files, releasing‬


‭database connections, etc.‬
‭●‬ ‭It‬‭always executes‬‭after the‬‭
try‬‭and‬‭
catch‬‭blocks,‬‭regardless of whether an‬
‭exception occurred or was handled.‬

‭ xample‬‭:‬
E
‭Java code‬
public class FinallyExample {‬

public static void main(String[] args) {‬

‭try {‬
‭int num = 10 / 0;‬
‭} catch (ArithmeticException e) {‬
‭System.out.println("Caught: " + e.getMessage());‬
‭} finally {‬
‭System.out.println("Finally block executed.");‬
‭}‬
}‬

}‬

‭Output‬‭:‬

‭aught: / by zero‬
C
Finally block executed.‬

‭4. What is the difference between‬‭


final‬‭,‬‭
finally‬‭, and‬‭
finalize()‬
‭?‬

‭Keyword/Method‬ ‭Purpose‬

final‬
‭ ‭ keyword used to declare constants, prevent method overriding, or‬
A
‭prevent inheritance.‬

finally‬
‭ ‭A block used for cleanup operations in exception handling.‬
finalize()‬
‭ ‭ method invoked by the garbage collector before an object is‬
A
‭destroyed (deprecated in Java 9).‬

‭5. What happens if an exception is thrown in a‬‭


finally‬‭block?‬

‭●‬ ‭If the‬‭


finally‬‭block itself throws an exception, it will override any previously thrown‬
‭exception from the‬‭
try‬‭or‬‭catch‬‭blocks.‬

‭ xample‬‭:‬
E
‭Java code‬
public class FinallyExceptionExample {‬

public static void main(String[] args) {‬

‭try {‬
‭throw new ArithmeticException("Exception from try");‬
‭} finally {‬
‭throw new NullPointerException("Exception from‬
finally");‬

‭}‬
}‬

}‬

‭Output‬‭:‬

‭xception in thread "main" java.lang.NullPointerException: Exception‬


E
from finally‬

‭6. Can we have a‬‭


try‬‭block without a‬‭
catch‬‭block?‬

‭●‬ ‭Yes‬‭, but it must be followed by a‬‭


finally‬‭block.‬

‭ xample‬‭:‬
E
‭Java code‬
public class TryWithoutCatchExample {‬

public static void main(String[] args) {‬

‭try {‬
‭System.out.println("Try block executed");‬
‭} finally {‬
‭System.out.println("Finally block executed");‬
‭}‬
}‬

}‬

‭Output‬‭:‬

‭ry block executed‬


T
Finally block executed‬

‭7. How are exceptions handled in multithreaded applications?‬

‭●‬ E ‭ ach thread has its own‬‭call stack‬‭, and exceptions must be handled within the‬
‭thread itself.‬
‭●‬ ‭If an exception occurs in one thread, it doesn't affect other threads.‬

‭ xample‬‭:‬
E
‭Java code‬
public class MultiThreadExceptionExample extends Thread {‬

public void run() {‬

‭try {‬
‭System.out.println("Thread running: " +‬
Thread.currentThread().getName());‬

‭int num = 10 / 0; // Causes ArithmeticException‬
‭} catch (ArithmeticException e) {‬
‭System.out.println("Exception caught in thread: " +‬
Thread.currentThread().getName());‬

‭}‬
}‬

public static void main(String[] args) {‬



‭MultiThreadExceptionExample t1 = new‬
MultiThreadExceptionExample();‬

‭t1.start();‬
}‬

}‬

‭8. What are common mistakes in exception handling?‬


‭ .‬ ‭Catching generic exceptions‬‭like‬‭
1 Exception‬‭or‬‭
Throwable‬‭.‬
‭Java code‬
‭/ Bad Practice‬
/
try {‬

int num = 10 / 0;‬

} catch (Exception e) {‬

System.out.println("Exception caught");‬

}‬

‭ .‬ ‭Empty catch blocks‬‭.‬


2
‭Java code‬
‭/ Bad Practice‬
/
try {‬

int num = 10 / 0;‬

} catch (ArithmeticException e) {‬

// No error message‬

}‬

‭3.‬ ‭Ignoring exceptions or logging them without actionable messages.‬

You might also like