🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › advantages.html
Advantages of Exceptions (The Java™ Tutorials > Essential Java Classes > Exceptions)
The FileNotFoundException class has no descendants, so the following handler can handle only one type of exception. ... A method can catch an exception based on its group or general type by specifying any of the exception's superclasses in the catch statement.
🌐
TutorialsPoint
tutorialspoint.com › importance-of-proper-exception-handling-in-java
Importance of Proper Exception Handling in Java
Proper exception handling is a ... and efficient code. It ensures the continuity of the program, enhances the robustness of the program, improves the readability and maintainability of the code, and allows for more accurate error reporting....
People also ask

What is an exception class in Java?
The Exception class and its derived classes represent a type of Throwable indicating situations that a well-designed application may need to handle.
🌐
herovired.com
herovired.com › home page › blogs › exception handling in java: advantages and examples
Exception Handling in Java: Advantages and Examples
What is throw and throws in Java?
Here is the difference between Throw and Throws in Java. The 'throw' keyword in Java enables explicit exception throwing within code, within a function or code block. On the other hand, the 'throws' keyword in Java is utilised in method signatures to declare potential exceptions that may arise during code execution.
🌐
herovired.com
herovired.com › home page › blogs › exception handling in java: advantages and examples
Exception Handling in Java: Advantages and Examples
What are checked and unchecked exceptions?
Checked exceptions occur during the compilation process, where the source code is translated into executable code. On the other hand, unchecked exceptions occur during runtime once the executable program is in operation.
🌐
herovired.com
herovired.com › home page › blogs › exception handling in java: advantages and examples
Exception Handling in Java: Advantages and Examples
🌐
GeeksforGeeks
geeksforgeeks.org › java › exceptions-in-java
Java Exception Handling - GeeksforGeeks
Unchecked Exception: These exceptions are checked at runtime and do not require explicit handling at compile time. To know more about Checked and Unchecked Exception -> Checked and Unchecked Exception · Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, users can also create exceptions, which are called "user-defined Exceptions". printStackTrace(): Prints the full stack trace of the exception, including the name, message and location of the error.
Published   December 23, 2016
🌐
Hero Vired
herovired.com › home page › blogs › exception handling in java: advantages and examples
Exception Handling in Java: Advantages and Examples
July 2, 2024 - Java, the beloved language of programmers worldwide, boasts a robust system for handling exceptions, akin to a seasoned firefighter calmly quenching flames amidst chaos. Exception handling in Java is like having a safety net woven with precision, ready to catch errors before they escalate into a full-blown crisis.
🌐
Great Learning
mygreatlearning.com › blog › it/software development › exception handling in java with examples – 2025
Exception Handling in Java with Examples | 2025 - Great Learning
January 6, 2025 - Exception handling in java helps in minimizing exceptions and helps in recovering from exceptions. It is one of the powerful mechanisms to handle runtime exceptions and makes it bug-free.
🌐
Vlabs
java-iitd.vlabs.ac.in › exp › exceptions › theory.html
Exception Handling in Java - Virtual Labs
It is an object which is thrown at runtime. Exception Handling is a mechanism to handle runtime errors such a ClassNotFoundException, IOException, SQLException, RemoteException, etc. The core advantage of exception handling is to maintain the normal flow of the application.
🌐
MIT
web.mit.edu › java_v1.0.2 › www › tutorial › java › exceptions › definition.html
What's an Exception and Why Do I Care?
If the runtime system exhaustively searches all of the methods on the call stack without finding an appropriate exception handler, the runtime system (and consequently the Java program) terminates. By using exceptions to manage errors, Java programs have the following advantages over traditional ...
🌐
Justacademy
justacademy.co › public › blog-detail › advantages-of-exception-handling-in-java
Advantages of Exception Handling in Java
5) By using try catch blocks, ... condition. 6) Exception handling promotes robustness in Java programs by forcing developers to anticipate and respond to potential errors proactively....
Find elsewhere
🌐
IIT Kanpur
iitk.ac.in › esc101 › 05Aug › tutorial › essential › exceptions › advantages.html
Advantages of Exceptions
The FileNotFoundException class has no descendants, so the following handler can handle only one type of exception: catch (FileNotFoundException e) { ... } A method can catch an exception based on its group or general type by specifying any of the exceptions superclasses in the catch statement.
🌐
CSE Department
cse.poriyaan.in › topic › exception-handling-50457
Exception Handling - Benefits, Hierarchy, Types, Keywords used, Example Java Programs
Inside a try block as soon as the statement: b=a/0 gets executed then an arithmetic exception must be raised, this exception is caught by a catch block. Thus there must be a try-catch pair and catch block should be immediate follower of try statement. After execution of catch block the control must come on the next line. These are basically the exceptions thrown by java runtime systems. Following are the benefits of exception handling -
🌐
E Computer Notes
ecomputernotes.com › home › java › exception › advantages of the exception-handling mechanism
Advantages of the Exception-Handling Mechanism - Computer Notes
September 5, 2020 - The ability to propagate errors up the call stack Another important advantage of exception handling in object oriented programming is the ability to propagate errors up the call stack.
🌐
Alibaba Cloud
topic.alibabacloud.com › a › the-advantages-and-disadvantages-of-exception-handling-in-java-programming_1_27_10105075.html
The advantages and disadvantages of exception handling in Java programming
Good exception handling provides a uniform mechanism for handling program errors. In fact, the Java language significantly improves the ability of exception handling in software development by presenting an exception warning to callers. This approach extends and enhances the method in the Java ...
🌐
Javatpoint
javatpoint.com › exception-handling-in-java
Exception Handling in Java
Exception Handling in Java or Java Exceptions with checked, unchecked and errors with example and usage of try, catch, throw, throws and finally keywords.
Top answer
1 of 2
5

It's three questions, but it's not like that's the first time that's happened here. :-)

  1. Yes, you must handle them or declare them, because they're checked exceptions. The reason you must do that is so that the code calling your code knows the ways in which your code may fail (because you've declared the exceptions it can throw).

  2. That snippet is very simple, so the separation and benefit aren't all that clear. But consider opening two streams, copying from one to another, with transformation code (including calls to subordinate methods). You end up with a method body with 10-20 statements in it. Instead of every I/O statement having to check whether it worked or not, you just write your logic wrapped in an IOException handler, knowing that any I/O exceptions will jump out of the main logic into the handler.

  3. It depends on what kind of program you're writing, but in general you handle exceptions at the most appropriate level, which is typically at multiple levels in your program. The outermost level, which is only to deal with really, really unusual, unrecoverable exceptions, would either just let the default handling do what it does, or use a catch-all handler that does something similar but might (attempt to) record the failure elsewhere (like a log file) as well:

    public class MyProgram {
        public static final void main(String[] args) {
           try {
               // Run...
           }
           catch (Throwable t) {
               // Handle the fact that something went wrong here, if you can
               // Usually this would be only for really, really unusual errors,
               // otherwise you would have handled them earlier
           }
        }
    }
    

To underscore the point in #2, consider two process methods, one in Java with exceptions, and the other in a hypothetical Java-like language that doesn't have exceptions:

The Java one:

private void process() {
    try (                                                // <== Main logic
        Reader fr = new FileReader(this.sourceFileName); // <== Main logic
        BufferedReader br = new BufferedReader(fr);      // <== Main logic
        Writer fw = new FileWriter(this.destFileName);   // <== Main logic
        BufferedWriter bw = new BufferedWriter(fw)       // <== Main logic
        ) {                                              // <== Main logic
        String line;                                     // <== Main logic
        while ((line = br.readLine()) != null) {         // <== Main logic
            if (shouldIncludeLine(line)) {               // <== Main logic
                line = transformLine(line);              // <== Main logic
                bw.write(line);                          // <== Main logic
                bw.newLine();                            // <== Main logic
            }                                            // <== Main logic
        }                                                // <== Main logic
    }
    catch (FileNotFoundException fnfe) {                 // <== Error handling
        // Couldn't find a file                          // <== Error handling
        // (handle it)                                   // <== Error handling
    }                                                    // <== Error handling
    catch (IOException ioe) {                            // <== Error handling
        // I/O error                                     // <== Error handling
        // (handle it)                                   // <== Error handling
    }                                                    // <== Error handling
    catch (Exception e) {                                // <== Error handling
        // Something else went wrong                     // <== Error handling
        // (handle it)                                   // <== Error handling
    }                                                    // <== Error handling
}

The hypothetical Java-like language without exceptions one:

// THIS IS FAKE, PSEUDO-JAVA
private Errors process() {
    Reader fr = new FileReader(this.sourceFileName);            // <== Main logic
    if (fr == null) {                                           // <== Error handling
        return Errors.CantOpenSource;                           // <== Error handling
    }                                                           // <== Error handling
    BufferedReader br = new BufferedReader(fr);                 // <== Main logic

    Writer fw = new FileWriter(this.destFileName);              // <== Main logic
    if (fw == null) {                                           // <== Error handling
        br.close();                                             // <== Error handling
        return Errors.CantOpenDest;                             // <== Error handling
    }                                                           // <== Error handling
    BufferedWriter bw = new BufferedWriter(fw)                  // <== Main logic

    String line;                                                // <== Main logic
    while ((line = br.readLine()) != IO.END_OF_FILE) {          // <== Main logic
        if (line == null) {                                     // <== Error handling
            br.close();                                         // <== Error handling
            bw.close();                                         // <== Error handling
            return Errors.CantRead;                             // <== Error handling
        }
        if (shouldIncludeLine(line)) {                          // <== Main logic
            line = transformLine(line);                         // <== Main logic
            if (bw.write(line) == -1 || bw.newLine() == -1) {   // <== Main logic (plus some error handling)
                br.close();                                     // <== Error handling
                bw.close();                                     // <== Error handling
                return Errors.CantWrite;                        // <== Error handling
            }
        }
    }

    bw.close();
    br.close();
    return Errors.Success;
}

Notice:

  • How the main logic is littered with error handling, making it harder to read and follow.
  • Special "error" return values are necessary for any method that might possibly have some kind of failure mode. We had to add one to process, and then we check for null from new FileReader and such, and check for -1 from read and write ops, etc.

If you're interested, here's a full version of the Java program vs. the full version of the not-really-Java program:

Java:

import java.io.*;

public class Example
{
    private String sourceFileName;
    private String destFileName;

    public static void main (String[] args) throws java.lang.Exception
    {
        try {
            new Example(args[0], args[1]).process();
        }
        catch (ArrayIndexOutOfBoundsException npe) {
            // This is a bit of an exaggeration, I'd check in advance, since the user not
            // supplying arguments isn't really an "exceptional" condition.
            System.out.println("Usage: java Example [source file name] [dest file name]");
        }
    }

    public Example(String src, String dest) {
        // Similar, these checks would probably be assertions, but I'm making a point...
        if (src == null || src.length() == 0) {
            throw new IllegalArgumentException("src must be non-null and non-blank");
        }
        if (dest == null || dest.length() == 0) {
            throw new IllegalArgumentException("dest must be non-null and non-blank");
        }
        this.sourceFileName = src;
        this.destFileName = dest;
    }

    private void process() {
        try (                                                // <== Main logic
            Reader fr = new FileReader(this.sourceFileName); // <== Main logic
            BufferedReader br = new BufferedReader(fr);      // <== Main logic
            Writer fw = new FileWriter(this.destFileName);   // <== Main logic
            BufferedWriter bw = new BufferedWriter(fw)       // <== Main logic
            ) {                                              // <== Main logic
            String line;                                     // <== Main logic
            while ((line = br.readLine()) != null) {         // <== Main logic
                if (shouldIncludeLine(line)) {               // <== Main logic
                    line = transformLine(line);              // <== Main logic
                    bw.write(line);                          // <== Main logic
                    bw.newLine();                            // <== Main logic
                }                                            // <== Main logic
            }                                                // <== Main logic
        }
        catch (FileNotFoundException fnfe) {                 // <== Error handling
            // Couldn't find a file                          // <== Error handling
            // (handle it)                                   // <== Error handling
        }                                                    // <== Error handling
        catch (IOException ioe) {                            // <== Error handling
            // I/O error                                     // <== Error handling
            // (handle it)                                   // <== Error handling
        }                                                    // <== Error handling
        catch (Exception e) {                                // <== Error handling
            // Something else went wrong                     // <== Error handling
            // (handle it)                                   // <== Error handling
        }                                                    // <== Error handling
    }

    private boolean shouldIncludeLine(String line) {
        return line.length() != 0;
    }

    private String transformLine(String line) {
        return line.toUpperCase();
    }
}

The hypothetical Java-like language without exceptions one:

// THIS IS FAKE, PSEUDO-JAVA WITHOUT EXCEPTIONS, IT ISN'T REAL
import java.io.*;

public class Example
{
    private String sourceFileName;
    private String destFileName;

    private enum Errors {
        Success,
        CantOpenSource,
        CantOpenDest,
        CantRead,
        CantWrite
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        if (args.length < 2) {
            System.out.println("Usage: java Example [source file name] [dest file name]");
        }
        if (args[0] == null || args[0].length() == 0) {
            throw new IllegalArgumentException("src must be non-null and non-blank");
        }
        if (args[1] == null || args[1].length() == 0) {
            throw new IllegalArgumentException("dest must be non-null and non-blank");
        }
        switch (new Example(args[0], args[1]).process()) {
            case Errors.CantOpenSource:
                // Handle it
                break;
            case Errors.CantOpenDest:
                // Handle it
                break;
            case Errors.CantRead:
                // Handle it
                break;
            case Errors.CantWrite:
                // Handle it
                break;
        }
    }

    public Example(String src, String dest) {
        // Not how now this constructor is trusting that it is called with valid arguments
        this.sourceFileName = src;
        this.destFileName = dest;
    }

    private Errors process() {
        Reader fr = new FileReader(this.sourceFileName);            // <== Main logic
        if (fr == null) {                                           // <== Error handling
            return Errors.CantOpenSource;                           // <== Error handling
        }                                                           // <== Error handling
        BufferedReader br = new BufferedReader(fr);                 // <== Main logic

        Writer fw = new FileWriter(this.destFileName);              // <== Main logic
        if (fw == null) {                                           // <== Error handling
            br.close();                                             // <== Error handling
            return Errors.CantOpenDest;                             // <== Error handling
        }                                                           // <== Error handling
        BufferedWriter bw = new BufferedWriter(fw)                  // <== Main logic

        String line;                                                // <== Main logic
        while ((line = br.readLine()) != IO.END_OF_FILE) {          // <== Main logic
            if (line == null) {                                     // <== Error handling
                br.close();                                         // <== Error handling
                bw.close();                                         // <== Error handling
                return Errors.CantRead;                             // <== Error handling
            }
            if (shouldIncludeLine(line)) {                          // <== Main logic
                line = transformLine(line);                         // <== Main logic
                if (bw.write(line) == -1 || bw.newLine() == -1) {   // <== Main logic (plus some error handling)
                    br.close();                                     // <== Error handling
                    bw.close();                                     // <== Error handling
                    return Errors.CantWrite;                        // <== Error handling
                }
            }
        }

        bw.close();
        br.close();
        return Errors.Success;
    }

    private boolean shouldIncludeLine(String line) {
        return line.length() != 0;
    }

    private String transformLine(String line) {
        return line.toUpperCase();
    }
}
2 of 2
1

1) If it's unreasonable for your code to be able to handle an exception, you can catch the checked exceptions thrown from your API calls and wrap them in an unchecked exception. Make sure you save the original checked exception as a cause in the new unchecked exception.

2) Your example snippet is not separating error-handling from business logic, it's glomming them together and obfuscating the result. There are two benefits of throwing the arithmetic exception here rather than passing back a default value: a) it's too difficult to distinguish a value passed to flag an error from a value that is the result of a valid computation and b) further business logic steps may depend on having calculated a valid value here, in which case you will have to leave the current flow anyway, you might as well use the exception for that.

3) It depends on the application. For a simple console program sometimes the best thing to do is let the error terminate the program. For a web application exceptions usually bubble up to a global exception handler, terminating that request but letting other requests proceed. For unit tests an exception is caught by the test runner and logged so that other tests can proceed.

🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › index.html
Lesson: Exceptions (The Java™ Tutorials > Essential Java Classes)
See Dev.java for updated tutorials taking advantage of the latest releases. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases. The Java programming language uses exceptions to handle errors and other exceptional events.
Top answer
1 of 4
8

Suppose you have func1 calling func2 with some input.

Now, suppose func2 fails for some reason.

Your suggestion is to handle the failure within func2, and then return to func1.

How will func1 "know" what error (if any) has occurred in func2 and how to proceed from that point?

The first solution that comes to mind is an error-code that func2 will return, where typically, a zero value will represent "OK", and each of the other (non-zero) values will represent a specific error that has occurred.

The problem with this mechanism is that it limits your flexibility in adding / handling new error-codes.

With the exception mechanism, you have a generic Exception object, which can be extended to any specific type of exception. In a way, it is similar to an error-code, but it can contain more information (for example, an error-message string).

You can still argue of course, "well, what's the try/catch for then? why not simply return this object?".

Fortunately, this question has already been answered here in great detail:

In C++ what are the benefits of using exceptions and try / catch instead of just returning an error code?

In general, there are two main advantages for exceptions over error-codes, both of which are different aspects of correct coding:

  1. With an exception, the programmer must either handle it or throw it "upwards", whereas with an error-code, the programmer can mistakenly ignore it.

  2. With the exception mechanism you can write your code much "cleaner" and have everything "automatically handled", wheres with error-codes you are obliged to implement a "tedious" switch/case, possibly in every function "up the call-stack".

2 of 4
7

Exceptions are a more object-oriented approach to handling exceptional execution flows than return codes. The drawback of return codes is that you have to come up with 'special' values to indicate different types of exceptional results, for example:

public double calculatePercentage(int a, int b) {
    if (b == 0) {
        return -1;
    }
    else {      
        return 100.0 * (a / b);
    }
}

The above method uses a return code of -1 to indicate failure (because it cannot divide by zero). This would work, but your calling code needs to know about this convention, for example this could happen:

public double addPercentages(int a, int b, int c, int d) {
    double percentage1 = calculatePercentage(a, b);
    double percentage2 = calculatePercentage(c, c);
    return percentage1 + percentage2;
}

Above code looks fine at first glance. But when b or d are zero the result will be unexpected. calculatePercentage will return -1 and add it to the other percentage which is likely not correct. The programmer who wrote addPercentages is unaware that there is a bug in this code until he tests it, and even then only if he really checks the validity of the results.

With exceptions you could do this:

public double calculatePercentage(int a, int b) {
    if (b == 0) {
        throw new IllegalArgumentException("Second argument cannot be zero");
    }
    else {      
        return 100.0 * (a / b);
    }
}

Code calling this method will compile without exception handling, but it will stop when run with incorrect values. This is often the preferred way since it leaves it up to the programmer if and where to handle exceptions.

If you want to force the programmer to handle this exception you should use a checked exception, for example:

public double calculatePercentage(int a, int b) throws MyCheckedCalculationException {
    if (b == 0) {
        throw new MyCheckedCalculationException("Second argument cannot be zero");
    }
    else {      
        return 100.0 * (a / b);
    }
}

Notice that calculatePercentage has to declare the exception in its method signature. Checked exceptions have to be declared like that, and the calling code either has to catch them or declare them in their own method signature.

I think many Java developers currently agree that checked exceptions are bit invasive so most API's lately gravitate towards the use of unchecked exceptions.

The checked exception above could be defined like this:

public class MyCheckedCalculationException extends Exception {

   public MyCalculationException(String message) {
       super(message);
   }
}

Creating a custom exception type like that makes sense if you are developing a component with multiple classes and methods which are used by several other components and you want to make your API (including exception handling) very clear.

(see the Throwable class hierarchy)

🌐
W3Schools
w3schools.com › java › java_try_catch.asp
Java Exceptions (Try...Catch)
When an error occurs, Java will ... an exception (throw an error). Exception handling lets you catch and handle errors during runtime - so your program doesn't crash....
🌐
j-labs
j-labs.pl › home › tech blog › java exception handling: strategies and best practices
Java Exception Handling in Java Best Practices | j‑labs
October 9, 2025 - Exception handling is a critical aspect of Java programming that allows developers to manage errors and unexpected situations gracefully. Proper exception handling enhances the reliability and maintainability of the code.
🌐
DigitalOcean
digitalocean.com › community › tutorials › exception-handling-in-java
Exception Handling in Java | DigitalOcean
October 6, 2022 - Using Checked Exceptions has the advantage of assisting developers with understanding which exceptions you can expect and take appropriate action to handle them. Use Specific Exceptions – Base classes of Exception hierarchy don’t provide any useful information, that’s why Java has so many ...