[go: up one dir, main page]

0% found this document useful (0 votes)
36 views5 pages

Java Exception Handling Explained

An exception in Java disrupts the normal flow of execution and requires handling to prevent abrupt program termination. Java distinguishes between checked exceptions, which are recoverable and checked at compile time, and unchecked exceptions, which are programming errors checked at runtime. Exception handling improves code reliability and readability, allowing for graceful error management in various applications.

Uploaded by

insaneboi2006
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)
36 views5 pages

Java Exception Handling Explained

An exception in Java disrupts the normal flow of execution and requires handling to prevent abrupt program termination. Java distinguishes between checked exceptions, which are recoverable and checked at compile time, and unchecked exceptions, which are programming errors checked at runtime. Exception handling improves code reliability and readability, allowing for graceful error management in various applications.

Uploaded by

insaneboi2006
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

Java Exception Handling - Long Answers

Q16. What is an exception? Why we need to handle it? Demonstrate try,


catch and finally keywords with an example program.
An exception in Java is an event that disrupts the normal flow of the program’s execution. It
is an object that is thrown at runtime whenever something abnormal happens, such as
invalid user input, division by zero, or trying to access an array index out of bounds.
Without exception handling, the JVM terminates the program abruptly. Exception handling
allows us to gracefully manage such conditions.

Need for Exception Handling:


1. Prevents abnormal termination of the program.
2. Provides meaningful error messages.
3. Separates normal logic from error-handling logic.
4. Ensures resources are properly closed.
5. Makes applications reliable and fault-tolerant.

Keywords used:
- try: Block containing code that may cause exception.
- catch: Block that handles the exception.
- finally: Always executes whether an exception occurs or not.

In real-world applications, exception handling is considered one of the pillars of


robust software design. For example, in banking systems, exceptions help in
handling invalid transactions or insufficient balance. In web applications,
exceptions handle timeouts or connection failures gracefully. Java’s structured
approach using try, catch, and finally ensures that developers can anticipate
potential failures and handle them proactively, which increases reliability and
user trust.

Example Program:

class ExceptionDemo {
public static void main(String[] args) {
try {
int a = 10, b = 0;
int result = a / b;
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Exception caught: " + e);
} finally {
[Link]("Finally block executed.");
}
[Link]("Program continues after handling exception.");
}
}

Q17. Draw the exception hierarchy in Java starting from Throwable.


Explain why Java distinguishes between checked and unchecked
exceptions.
In Java, all exceptions are derived from the Throwable class. Throwable has two direct
subclasses: Exception and Error. Exception represents conditions that applications might
want to catch, while Error represents serious system-level problems.

Exception Branch:
- Checked Exceptions: Checked at compile time (e.g., IOException, SQLException).
- Unchecked Exceptions: Subclasses of RuntimeException, checked at runtime (e.g.,
NullPointerException).

Hierarchy:
Throwable
/ \
Error Exception
|
--------------------------
| |
Checked Exceptions Unchecked Exceptions
(IOException, (RuntimeException,
SQLException, etc.) NullPointerException)

Reason for Distinction:


- Checked exceptions are usually caused by external factors and are recoverable.
- Unchecked exceptions are due to programming mistakes and not always recoverable.
Additionally, this distinction also makes debugging easier, as developers can immediately
recognize whether the problem arises from an external factor (like missing files) or from an
internal logic error. The compiler’s enforcement of handling checked exceptions ensures
that important issues cannot be ignored. This design decision has made Java a more robust
language compared to others where error handling is optional or inconsistent.

Q18. What is exception handling? Explain the applications of exception


handling in java. Develop a program on exception handling mechanism.
Exception Handling in Java is a mechanism to deal with runtime errors in such a way that
the normal flow of the program is not disturbed. It ensures smooth execution and recovery.

Applications of Exception Handling:


Input Validation – Ensuring correct data from users.

File Handling – Handling missing files or read/write errors.

Database Operations – Managing failed queries or lost connections.

Network Programming – Handling timeouts and dropped connections.

Resource Management – Ensuring files, sockets, or DB connections are closed.

Debugging Support – Providing meaningful error messages and stack traces.

Moreover, exception handling improves code readability by clearly separating the normal
business logic from error-handling logic. Example Program:

import [Link];
class ExceptionExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try {
[Link]("Enter a number: ");
int num = [Link]();
int result = 100 / num;
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed.");
} catch (Exception e) {
[Link]("Some error occurred: " + [Link]());
} finally {
[Link]();
[Link]("Scanner closed. Finally block executed.");
}
}
}

Q19. Differentiate between checked and unchecked exception with a


suitable example.
Checked exceptions are checked at compile time, while unchecked exceptions are only
detected at runtime.

Comparison:
Checked Exception → Must be declared/handled, caused by external factors (IOException).
Unchecked Exception → Not mandatory to handle, caused by programming mistakes
(NullPointerException).

It is important to note that while checked exceptions ensure compile-time safety, unchecked
exceptions provide flexibility by not forcing developers to handle every minor issue. This
balance makes Java both strongly typed and developer-friendly. Typically, checked
exceptions are used for recoverable scenarios, whereas unchecked exceptions highlight
issues that should be corrected in code

Example:

// Checked Exception Example


import [Link].*;
class CheckedEx {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("[Link]");
BufferedReader br = new BufferedReader(fr);
[Link]([Link]());
[Link]();
}
}

// Unchecked Exception Example


class UncheckedEx {
public static void main(String[] args) {
int arr[] = new int[3];
[Link](arr[5]); // ArrayIndexOutOfBoundsException
}
}
Q24. What do you mean by exception and error? Give the hierarchy of
exceptions in java.
Both exceptions and errors are subclasses of Throwable.

Exception: Represents conditions that a program can handle and recover from (e.g.,
IOException, NullPointerException).

Error: Represents serious system-level problems beyond the control of the program (e.g.,
OutOfMemoryError, StackOverflowError).

Hierarchy:
Throwable
/ \
Exception Error
|
-----------------------------
| |
Checked Exceptions Unchecked Exceptions
(IOException, (RuntimeException,
SQLException, etc.) NullPointerException, etc.)

In practical applications, developers focus mainly on handling exceptions because errors


usually indicate conditions outside the control of the program. For example, an
OutOfMemoryError signals that the JVM has run out of memory, which cannot be fixed by
code. Exceptions like IOException, however, can be managed, such as by asking the user to
re-enter a [Link] the hierarchy helps developers design effective error-
handling strategies. The distinction ensures clarity.

You might also like