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

Java Exception Handling Explained

This article discusses Exception Handling in Java, explaining the concepts of errors, exceptions, and their types, including compile-time and run-time errors. It covers the importance of handling exceptions, the exception hierarchy, and how to implement exception handling in Java applications. Additionally, it differentiates between checked and unchecked exceptions, providing examples and scenarios for better understanding.
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)
17 views10 pages

Java Exception Handling Explained

This article discusses Exception Handling in Java, explaining the concepts of errors, exceptions, and their types, including compile-time and run-time errors. It covers the importance of handling exceptions, the exception hierarchy, and how to implement exception handling in Java applications. Additionally, it differentiates between checked and unchecked exceptions, providing examples and scenarios for better understanding.
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

Exception Handling in Java with Examples

In this article, I am going to discuss Exception Handling in Java with Examples. Whenever we
develop any application there is a chance of occurring errors in the application. As Java
developers, it is our key responsibility to handle the exception while developing an application.
At the end of this article, you will understand the following pointers in detail.

1. What is an Error?
2. Compile Time and Run time Errors
3. What is an Exception?
4. Why an exception occurs?
5. What happens when an exception is raised in the program?
6. What JVM does do when a logical mistake occurred in the program?
7. Exception Hierarchy in Java
8. What are the differences between Error and Exception?
9. Types of Exceptions in Java
10. Checked and Unchecked Exceptions in Java
11. What is exception handling in Java?
12. Why do we need Exception Handling in Java?
13. How can we handle an exception in Java?
14. Multiple catch blocks in Java
15. Can we catch all exceptions using a single catch block?
16. When should we write multiple catch blocks for a single try block?
17. How to display Exception or Runtime Error Message?

What is an Error?

An Error indicates a serious problem that a reasonable application should not try to catch.

We have the following two types of errors:

1. Compile Time Error

2. Run Time Error

Compile Time Error

Errors that occur at the time of compilation of the program are called compile-time errors.
Compile-time errors occurred because if we don’t follow the java syntaxes properly, java
programming rules properly, etc. Compile-time errors are identified by the java compiler. So in
simple words, we can say that compile-time errors occur due to a poor understanding of the
programming language. These errors can be identified by the programmer and can be rectified
before the execution of the program only. So these errors do not cause any harm to the
program execution.

Run Time Error

Errors that occur at the time of execution in the program are called runtime errors. Run-Time
Errors are also called Exceptions. Exceptions may occur because programmer logic fails or JVM
fails. Exceptions are identified by JVM.

Note: The Runtime errors are dangerous because whenever they occur in the program, the
program terminates abnormally on the same line where the error gets occurred without
executing the next line of code.

What is an Exception?

Exceptions are the run-time errors that occur during the execution of the program. The
exception will cause the abnormal termination of the program execution.

An Exception is an unwanted event that interrupts the normal flow of the program. When an
exception occurs program execution gets terminated. It is an object which is thrown at runtime.

Why an exception occurs?

These errors occurred when we enter the wrong data into a variable, try to open a file for
which there is no permission, try to connect to the database with the wrong user id and
password, the wrong implementation of logic, missing required resources, etc.

There can be several reasons that can cause a program to throw an exception.

For example: Opening a non-existing file in your program, Network connection problem, bad
input data provided by the user, etc.

Why do we need Exception?

Suppose you have coded a program to access the server. Things worked fine while you were
developing the code.
During the actual production run, the server is down. When your program tried to access it, an
exception is raised.

How to Handle Exception

So far we have seen, exception is beyond developer’s control. But blaming your code failure on
environmental issues is not a solution. You need a Robust Programming, which takes care of
exceptional situations. Such code is known as Exception Handler.

In our example, good exception handling would be, when the server is down, connect to the
backup server.
To implement this, enter your code to connect to the server (Using traditional if and else
conditions).

You will check if the server is down. If yes, write the code to connect to the backup server.

Such organization of code, using “if” and “else” loop is not effective when your code has
multiple java exceptions to handle.

class connect{

if(Server Up){

// code to connect to server

else{

// code to connect to BACKUP server

What happens when an exception is raised in the program?

Program execution is terminated abnormally. It means statements placed after exception-


causing statements are not executed but the statements placed before that exception-causing
statements are executed by JVM.

What JVM does do when a logical mistake occurred in the program?


It creates an exception class object that is associated with that logical mistake and terminates
the current method execution by throwing this exception object by using the “throw” keyword.

So we can say an exception is an event that occurs during the execution of a program that
disrupts the normal flow of instruction execution.

Example: The below example shows program execution without exception

public class ExceptionHandlingDemo

public static void main (String[]args)

int a = 20;

int b = 10;

[Link] ("a value = " + a);

[Link] ("b value = " + b);

int c = a / b;

[Link] ("c value = " + c);

Output:

Example: The following example shows program execution with the exception

public class ExceptionHandlingDemo

public static void main (String[]args)


{

int a = 20;

int b = 0;

[Link] ("a value = " + a);

[Link] ("b value = " + b);

int c = a / b;

[Link] ("c value = " + c);

}}

Output:

Explanation of the above Program:

After printing the value of a and b, JVM terminates this program execution by throwing
ArithmeticException because the logical mistake we committed is dividing integer numbers by
integer zero.

As we know it is not possible to divide an integer number by zero. But it is possible to divide a
number with double zero (0.0).

From the above program, we can define the exception technically as

1. An exception is an event because when an exception is raised JVM internally


executes some logic to prepare that exception-related messages.

2. The exception is a signal because by looking into the exception message


developer will take necessary actions against that exception.

3. An exception is an object because for throwing an exception, JVM or we should


create an appropriate class object.
Exception Hierarchy in Java

The [Link] class is the root class of the Java Exception hierarchy which is inherited
by two subclasses:

Exception and Error.

All exception and error types are subclasses of class Throwable, which is the base class of the
hierarchy.

One branch is headed by Exception. This class is used for exceptional conditions that user
programs should catch.

NullPointerException is an example of such an exception.

Another branch, Error is used by the Java run-time system(JVM) to indicate errors having to do
with the run-time environment itself(JRE).

StackOverflowError is an example of such an error.

A hierarchy of Java Exception classes is given below:

Here,

Object: Object is the super most class of all classes available in java.

Throwable: For all types of exceptions [Link] is the superclass.

It has two main subclasses

1. Error

2. Exception

Exception: Exception is the super most class of all exceptions that may occur because of
programmer logic failure. These exceptions we can handle.
Error: Error is the super-most class of all exceptions that occur because of JVM failure. These
errors we cannot handle.

What are the differences between Error and Exception?

An Exception is an exception that can be handled. It means when an exception happens the
programmer can do something to avoid any harm. But an Error is an exception that cannot be
handled. It means it happens and the programmer cannot do anything.

Let’s see in detail

Difference 1:
Error type exception is thrown due to the problem that occurred inside JVM logic, like If there is
no memory in the java stack area to create a new Stackframe to execute method then the JVM
process is killed by throwing Error type exception “[Link]”.

If there is no memory in the heap area to create a new object then the JVM process is killed by
throwing the Error type exception “[Link]”.

Exception type exceptions are thrown due to the problem that occurred in java program logic,
like If we divide an integer number with zero, then JVM terminates program execution by
throwing Exception type exception “[Link]”.

If we pass the array size as a negative number, then JVM terminates the program execution by
throwing the exception type exception “[Link]”.

Difference 2:

We cannot catch an Error type exception because an error type exception is not thrown in our
application and once this error type exception is thrown JVM is terminated.

We can catch an Exception type exception because an exception type exception is thrown in our
program and moreover JVM is not directly terminated because of an exception type exception.
JVM is only terminated if the thrown exception is not caught.
Types of Exceptions in Java:

We have the following two types of Exceptions:

1. Checked Exceptions

2. Unchecked Exceptions

Common questions

Powered by AI

In Java, 'Error' is related to serious issues arising primarily from the JVM's inability to continue execution, such as 'StackOverflowError' or 'OutOfMemoryError'. These are typically not recoverable and cannot be caught or handled by programs . 'Exception', however, is a condition affected by program logic errors or external input issues that can be anticipated and managed through exception handling, allowing the program to continue or terminate gracefully . Understanding this difference is crucial for developers because while errors generally indicate system state issues that need intervention beyond code fixes, exceptions can often be smoothly handled within the application code to ensure reliability and robustness.

The Java Virtual Machine (JVM) handles exceptions by first attempting to create an exception object and then terminate the current method execution by throwing the exception object using the 'throw' keyword. This process disrupts the normal flow of instruction execution and causes abnormal termination if not handled properly . Programmer logic exceptions, on the other hand, can be caught and managed through exception handling mechanisms provided in Java, such as try-catch blocks, allowing the programmer to avoid abnormal termination and execute an alternative flow .

The 'Throwable' class is the superclass of all errors and exceptions in the Java exception hierarchy. It provides the root functionalities for managing exceptional states. It is inherited by two subclasses: 'Error' for critical issues that JVM cannot handle, and 'Exception' for issues that occur due to incorrect logic or user input which can be handled programmatically . This hierarchical structure helps categorize and manage the different types of errors and exceptions that can occur, providing a systematic approach to error management in Java applications.

Runtime errors in Java, also known as exceptions, are considered more dangerous than compile-time errors because they occur during the execution of the program and can lead to abrupt program termination if not properly handled. These errors are not caught by the compiler, thus requiring developers to anticipate potential issues and implement appropriate exception handling mechanisms such as try-catch blocks . Compile-time errors, on the other hand, are detected by the compiler during code compilation, allowing them to be fixed before the program is run . To handle runtime errors effectively, developers should use robust exception handling strategies that ensure graceful program degradation and data integrity.

Understanding the Java exception hierarchy is critical for managing exceptions effectively in large software systems because it provides a structured framework for categorizing and handling various error conditions. The hierarchy distinguishes between system-level errors and application-specific exceptions, allowing developers to implement targeted exception handling strategies that enhance software reliability and maintainability . In large systems, clear understanding of this hierarchy helps ensure that all possible exceptions are accounted for and handled in ways that align with system behavior requirements and user expectations, minimizing the risk of unhandled exceptions causing system outages or failures.

Not properly handling exceptions in Java programs can lead to several negative consequences, including abrupt program termination, data corruption, resource leaks, and a degraded user experience. When runtime exceptions are unhandled, programs can crash without warning, leading to loss of unsaved work and inconsistent application states . For users, this means a loss of data or functionality, resulting in frustration and decreased trust in the software. Moreover, mishandled exceptions can complicate debugging and maintenance, increasing development costs and time due to the obscured root causes of errors.

Implementing a backup server connection during exception handling is critical for maintaining uninterrupted service in Java applications. This process involves first trying to connect to the primary server. If an exception indicating server unavailability occurs, such as a network error, the program can switch to a secondary server. This is typically done using exception handling techniques, such as try-catch blocks, to catch the initial connection exception and then attempt the backup connection within the catch block . This strategy ensures that the application remains resilient and maintains operational continuity even in the presence of unexpected server failures.

Realizing that 'Throwable' is the root of all error and exception classes in Java influences exception handling strategy by informing developers that errors and exceptions are two distinct yet related categories in the hierarchy. Exception handling strategies can then be designed to appropriately manage each category according to its characteristics: exceptions (controlled events) and errors (uncontrolled, critical conditions). Knowing that all exceptions and errors derive from 'Throwable' helps developers organize code to handle both recoverable (exceptions) and non-recoverable (errors) scenarios effectively, by using inheritance and polymorphism in exception classes.

While it is possible to catch a wide range of exceptions in Java using a single catch block by catching exceptions of type 'Exception', this approach can lead to imprecise error detection and handling. It captures all exceptions including unexpected ones, which can obscure the specific issues and make debugging difficult . The downside is that it doesn't allow for different handling mechanisms for different exceptions. Therefore, more precise handling through multiple catch blocks for specific exceptions is recommended to provide detailed responses to particular error situations.

Multiple catch blocks are essential when handling exceptions in scenarios where different types of errors require different responses or handling strategies. For example, a network-related exception may require retry logic, while a file access exception might merely need a user-friendly error message . This approach enhances code reliability by allowing precise and contextual error handling, thus reducing the risk of incorrect exception management and improving overall program robustness by ensuring appropriate responses to specific conditions.

You might also like