0% found this document useful (0 votes)
7 views11 pages

Java Exception Handling Overview

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views11 pages

Java Exception Handling Overview

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

‭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 [Link].*;‬

public class CheckedExceptionExample {‬



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

‭try {‬
‭FileReader file = new FileReader("[Link]");‬
‭} catch (FileNotFoundException e) {‬
‭[Link]("File not found: " + [Link]());‬
‭}‬
}‬

}‬

‭(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) {‬
‭[Link]("Error: " + [Link]());‬
‭}‬
}‬

}‬

‭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) {‬
‭[Link]("Caught: " + [Link]());‬
‭} finally {‬
‭[Link]("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");‬

‭}‬
‭[Link]("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 [Link].*;‬

public class ThrowsExample {‬



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

‭FileReader file = new FileReader("[Link]");‬
}‬

}‬

‭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) {‬
‭[Link]("Exception: " + [Link]());‬
‭}‬
}‬

static void checkAge(int age) throws InvalidAgeException {‬



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

‭}‬
‭[Link]("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) {‬
‭[Link]("ArithmeticException caught: " +‬
[Link]());‬

‭} catch (ArrayIndexOutOfBoundsException e) {‬
‭[Link]("ArrayIndexOutOfBoundsException‬
caught: " + [Link]());‬

‭}‬
}‬

}‬

‭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 [Link].*;‬

public class TryWithResourcesExample {‬



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

‭try (BufferedReader br = new BufferedReader(new‬
FileReader("[Link]"))) {‬

‭[Link]([Link]());‬
‭} catch (IOException e) {‬
‭[Link]("IOException: " + [Link]());‬
‭}‬
}‬

}‬

‭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) {‬
‭[Link]("Caught: " + [Link]());‬
‭}‬
}‬

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) {‬
‭[Link]("Caught: " + [Link]());‬
‭} finally {‬
‭[Link]("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" [Link]: 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 {‬
‭[Link]("Try block executed");‬
‭} finally {‬
‭[Link]("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 {‬
‭[Link]("Thread running: " +‬
[Link]().getName());‬

‭int num = 10 / 0; // Causes ArithmeticException‬
‭} catch (ArithmeticException e) {‬
‭[Link]("Exception caught in thread: " +‬
[Link]().getName());‬

‭}‬
}‬

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



‭MultiThreadExceptionExample t1 = new‬
MultiThreadExceptionExample();‬

‭[Link]();‬
}‬

}‬

‭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) {‬

[Link]("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.‬

Common questions

Powered by AI

The finally block in Java is used to perform cleanup operations that must occur after try-catch execution, such as closing files or releasing database connections. It ensures resources are freed and other necessary cleanup occurs regardless of whether an exception was thrown or handled. The finally block executes after the try and catch blocks, maintaining the application's stability even when exceptions are encountered .

Custom exceptions in Java are user-defined exceptions that extend Exception or RuntimeException classes, allowing specific exception handling that standard Java exceptions may not address. To create them, developers must extend the Exception class, providing a constructor for custom messages, enabling informative error reporting. Such tailored exceptions enhance code clarity and functionality by accurately representing specific error conditions .

Exception handling in Java consists of try-catch blocks, throw and throws statements, and the finally block. Try-catch blocks help manage exceptions by enclosing code that might throw exceptions and handling them within catch conditions. The throw statement is used to explicitly throw exceptions, enabling developers to handle abnormal situations programmatically. The throws keyword declares exceptions a method may throw, informing callers of potential exceptions. The finally block ensures code execution regardless of exceptions, typically for resource cleanup like closing files .

Exception propagation in Java involves passing an exception from one method to its caller if not handled within the current method. It continues up the call stack until caught or reaches the JVM, where the program terminates. Propagation underscores the importance of well-designed methods with exception-handling strategies. Developers should carefully decide where to catch exceptions based on program logic, as catching exceptions too early may prevent proper resolution, while catching too late could allow unnecessary program disruption .

Checked exceptions are caught at compile-time, enforcing handling through try-catch blocks or declaring them with throws, such as IOException and SQLException. In contrast, unchecked exceptions occur at runtime, without the compiler requiring explicit handling; these include NullPointerException and ArithmeticException. Unchecked exceptions are subclasses of RuntimeException, while checked exceptions are subclasses of Exception excluding RuntimeException. This structural distinction influences their detection and handling in Java programming .

In multithreaded Java applications, each thread possesses its own call stack, isolating exception handling to the individual thread. An exception in one thread does not directly affect others, necessitating independent handling within each thread's run method. Uncaught exceptions terminate the thread, emphasizing the importance of robust exception handling logic tailored to each thread's execution path, ensuring application stability and accurate error resolution .

Using specific exceptions rather than generic ones, such as Exception and Throwable, is recommended to precisely identify and handle exceptions with tailored responses. Catching generic exceptions can mask specific issues, making debugging difficult and potentially leading to inappropriate handling of underlying problems. Specific exceptions, on the other hand, allow for targeted action and clearer understanding of errors, improving code reliability and maintainability .

If an exception occurs within a finally block, it can suppress any exceptions from the try or catch blocks, making it the final exception to be thrown. This behavior can lead to loss of original exception information unless properly managed. For example, if a try block throws an ArithmeticException, but the finally block subsequently throws a NullPointerException, the latter is raised, overshadowing the initial exception .

In Java, multiple catch blocks follow a single try block to handle different exception types. The order is crucial as more specific exceptions must precede more general ones due to Java's top-down approach in catch block execution. If a general exception is caught first, specific exceptions of the same hierarchy would never be reached. This order ensures accurate exception trapping and handling, preventing overlooked exceptions and potential logic errors .

The try-with-resources statement simplifies resource management by automatically closing resources, such as streams and files, that implement the AutoCloseable or Closeable interfaces, after the try block finishes. Unlike traditional try-catch-finally, it reduces boilerplate code for resource cleanup and minimizes errors associated with manually closing resources. This constructs improves efficiency, readability, and reliability of code by ensuring resources are properly closed even in the presence of exceptions .

You might also like