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

Knowing Java

NOTHING

Uploaded by

2309401007.jyoti
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Knowing Java

NOTHING

Uploaded by

2309401007.jyoti
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Checked Exceptions

Knowing Java's Checked Exceptions


One of the most notable aspects of Java's robust type system is its
exception handling mechanism. There are two categories for
exceptions in Java: verified exceptions and unchecked exceptions.
This article explores checked exceptions, including their definition,
purpose, benefits, drawbacks, and optimal handling techniques.

What Do Checked Exceptions Entail? 1.


Checked exceptions are exceptions that the Java compiler verifies
during compilation. This indicates that methods must handle these
exceptions or declare them using the throws keyword in the method
signature in order for the compiler to need them. The program will
not compile if a method throws a checked exception and does not
handle it or declare it.

Typical instances of verified exceptions are as follows:

IOException
SQL Error
NoClassNotFoundException
For instance:
Java
Copy the public void code. fileReader file = new FileReader(filePath);
BufferedReader fileInput = new BufferedReader(file); readFile(String
filePath) throws IOException {

// Output the file's contents using


System.out.println(fileInput.readLine());

close() fileInput; }
The readFile function in this instance may throw an IOException.
Either a try-catch block must handle this exception, or the throws
keyword must be used to indicate it, as demonstrated here.

2. Why Do Checked Exceptions Exist?


To enforce error management, the notion of checked exceptions was
added. Java's creators sought to make sure that probable mistake
scenarios—like missing files or problems connecting to databases—
would not go unnoticed by programmers. Their goal was to make
Java applications more resilient by mandating that checked
exceptions be handled or declared.

Important Checked Exceptions Features:


Enforced Handling: Checked exceptions make sure that programmers
consider error handling right away. In order to avoid runtime issues
caused by unhandled exceptions, the compiler makes sure that every
checked exception is handled or declared.
Predictability: Since checked exceptions are clearly stated in the
method signature, they aid developers in understanding the types of
mistakes that may arise in a method.

3. How Are Checked Exceptions Handled?


In Java, checked exceptions can be handled in two major ways:

The most popular method for handling checked exceptions is to use a


try-catch block to handle the exception. It entails enclosing the
possibly dangerous code in a try block and including one or more
catch blocks to deal with any potential exceptions.
For instance:
Java
Copy the public void code. readFile(String filePath) { try { FileReader
file = new FileReader(filePath); BufferedReader fileInput = new
BufferedReader(file);

// Output the file's contents using


System.out.println(fileInput.readLine());

catch (IOException e) { System.out.println("An error occurred while


reading the file: " + e.getMessage()); ` fileInput.close(); }
Utilize the throws keyword to declare the exception: This transfers
the burden of managing the exception to the method's caller.
For instance:
Java
Public void procedure copy codeString filePath file() IOException is
thrown by readingFile(filePath);

FileReader file = new FileReader(filePath); public void readFile(String


filePath) throws IOException
fileInput for BufferedReader = new BufferedReader(file);

// Output the file's contents using


System.out.println(fileInput.readLine());

close() fileInput; }
In this example, the processFile method additionally specifies that it
throws the same exception without processing it, in addition to the
readFile method's declaration that it throws an IOException.
4. Verified versus Unverified Exceptions
Exceptions in Java fall into two main categories:

Exceptions that are verified during compilation are known as checked


exceptions. As previously mentioned, the developer must deal with
them or declare them.

Runtime exceptions, sometimes referred to as unchecked exceptions,


are not examined by the compiler. ArrayIndexOutOfBoundsException,
NullPointerException, and IllegalArgumentException are a few of
these. Programming problems are typically represented by
unchecked exceptions, which the developer is not obligated to
manage or report.
Example :-
public void divide(int a, int b) {
System.out.println(a / b); // May throw ArithmeticException if b is
zero
}

5. Benefits of Checked Exception


Enforces Robust mistake Handling: By making you handle exceptions,
the compiler makes sure that important mistake scenarios are not
overlooked, which results in programs that are more reliable and
predictable.

Unambiguous Error Communication: By include checked exceptions


in method signatures, you give other developers—or yourself in the
future—clear instructions about the kinds of errors that might occur
with the method.
Promotes Error Recovery: Instead of letting your software crash when
an error occurs, checked exceptions force you to consider how it
should recover.

6. Drawbacks of Checked Exceptions Verbose


Code: Because you have to handle or declare each and every
potential checked exception that can arise, checked exceptions
frequently result in excessively verbose code. This may cause
"clutter" in the codebase, particularly if numerous exceptions need to
be handled in various locations.

Error Propagation: Instead of handling exceptions at the point of


occurrence, developers occasionally propagate them up the call stack
since methods must declare each checked exception. This may lead
to less significant exception handling and make it more difficult to
identify the source of issues.

Overused in Legacy APIs: Checked exceptions are widely utilized in


several older Java APIs, including file handling and database
connectivity. In order to simplify code and minimize verbosity,
modern best practices frequently recommend utilizing unchecked
exceptions for a variety of mistake circumstances.

7. Optimal Methods for Employing Checked


Exceptions
For circumstances that can be recovered, use checked exceptions:
When the client is capable of recovering from the exception, checked
exceptions ought to be utilized. For instance, the application may ask
the user to supply the appropriate file if one is missing.

A word of caution: Don't use checked exceptions excessively in


situations where there is no way to recover. Prefer unchecked
exceptions if an error indicates a programming error or an illegal
state (such as null values passed where they shouldn't be).

Handle exceptions appropriately: In your application, handle


exceptions at the proper level. Unless the caller is able to handle
exceptions in a meaningful way, do not propagate exceptions blindly
up the call stack.

To specify meaningful exceptions, use throws: Be explicit when


defining exceptions in method signatures. Overuse of general
exceptions (e.g., Throwable, Exception) can mask the true nature of
the issue.

Checked exceptions should be either logged or wrapped before being


thrown again if you manage to catch one but are unable to handle it.
In addition to preserving program flow, this can help gather
important details about the error.

For instance, Java


The code is copied as follows: public void readFile(String filePath) {
try�
FileReader(filePath) file = new FileReader;
fileInput for BufferedReader = new BufferedReader(file);

// Output the file's contents using


System.out.println(fileInput.readLine());
close() fileInput; catch (IOException e) raise new
FileReadException("Error reading file: " + filePath, e); } // Wrap in a
custom unchecked exception and rethrow }

7. Best Practices for Using Checked Exceptions


Use checked exceptions when there are situations that can be
resolved: Checked exceptions should be used when the client is able
to recover from the exception. For example, if a file is missing, the
application might ask the user to provide it.

A word of caution: In cases when recovery is not possible, avoid using


checked exceptions extensively. If an error implies a programming
fault or an illegal state (e.g., null values passed where they shouldn't
be), prefer unchecked exceptions.

Treat exceptions correctly: Make sure that exceptions are handled


effectively in your application. Do not propagate exceptions blindly
up the call stack unless the caller can handle exceptions in a
meaningful fashion.

Use throws to define meaningful exceptions: When declaring


exceptions in method signatures, be specific. The underlying nature
of the problem may be hidden by the overuse of general exceptions
(such as Throwable and Exception).

If you catch a checked exception but are not able to handle it, it
should be either logged or wrapped before being thrown again. This
can assist in obtaining crucial information regarding the problem in
addition to maintaining program flow.

As an example, Java
The following is a copy of the code: readFile(String filePath) is a
public void that can be used to try different things. For example,
FileReader(filePath) file = new FileReader; fileInput for
BufferedReader = new BufferedReader(file);

// Using System.out.println(fileInput.readLine()), output the contents


of the file;

fileInput.close(); catch (IOException e) { // Construct a custom


unchecked exception and rethrow raise new
FileReadException("Error reading file: " + filePath, e); }

8. Verified Exemptions in Contemporary Java


The community's view on checked exceptions has changed a little as
Java has developed. They are overused, according to many
developers, especially in older libraries. Certain contemporary
libraries, such as Spring, prioritize simplicity over verified exceptions.
Moreover, Java 8 brought new features like streams and lambda
expressions, which might occasionally complicate handling checked
exceptions.

utilizing functional interfaces that don't throw checked exceptions or


utilizing wrappers to turn checked exceptions into unchecked ones
are two ways to address this issue.

Lambdas example: Java Copy code List Arrays.asList("file1.txt",


"file2.txt"); fileNames;

forEach(fileName -> fileNames) attempt { readFile(fileName); catch


(IOException e) { throw new RuntimeException(e); } });
To make using lambda expressions easier, the checked IOException in
this example is wrapped in an unchecked RuntimeException.
Current Patterns and Options :-
Checked exceptions have been replaced in recent years by unchecked
exceptions or alternative error-handling techniques like Optional,
Either, or monadic error handling by a large number of developers
and frameworks. Instead of rigorously requiring error handling at the
language level, these approaches encourage developers to handle
errors when appropriate and offer more flexibility.

Checked exceptions are completely avoided in languages like Kotlin,


Scala, and others, which reflects the trend toward handling mistakes
at a higher abstraction level or regarding exceptions as exceptional,
infrequent events that should cause the application to terminate.

In summary
When utilized properly, checked exceptions can strengthen code
robustness by providing an organized means of enforcing error
management. However, because of its rigidity, boilerplate code and
needless complexity are frequently produced, which can be
frustrating and misused. Although checked exceptions are meant to
encourage better programming habits, many developers now choose
more flexible alternatives since they allow for cleaner, more
maintainable code because of checked exceptions' limitations. The
decision between checked and unchecked exceptions is still up for
debate, with the development team's attitude and the particular
requirements of a project playing a major role.

You might also like