❌

Reading view

There are new articles available, click to refresh the page.

Exception Handling

What is Exception?

An Exception is an unexpected or unwanted event which occurs during the execution of a program that typically disrupts the normal flow of execution.

This is definition OK but what I understand : The program’s execution is getting stopped abnormally when it reaches some point which have some mistake/error – it may be small or big, compilation or runtime or logical mistake. And its not proceeding with further statements. Handling this situation is called exception handling. Cool. Isn’t it?

Why Exception Handling?

If we do not handle the exception program execution will stop. To make the program run smoothly and avoid stopping due to minor issues/exceptions, we should handle it.

So, how it is represented, In Java everything is class, right? The derived classes of java.lang.Throwable are Error and Exception. For better understanding lets have a look at the hierarchical structure.

Here I could see Exception and Error – when we hear these words looks similar right. So What could be the difference?

Errors are some serious issues which is beyond our control like System oriented errors. Ex. StackOverFlowError, OutOfMemoryError (Lets discuss this later).

Exception is a situation which we can handle,

  1. through try-catch-(finally) block of code
  2. Throws keyword in method signature.

try-catch-Finally :

What is the meaning? As we are the owner of our code, we do have some idea about the possible problems or exceptions which we can solve or handle through this try-catch block of code.

For Ex. Task : Make a Tasty Dish.

What could be the exceptions?

  1. Some spice added in lower quantity.
  2. Chosen vessel may be smaller in size
  3. some additional stuff may not be available

To overcome these exception we can use try-catch block.

try {
  Cooking_Process();
}
catch(VesselException chosenLittle) {
   Replace_with_Bigger_One();
}
catch(QtyException_Spice spiceLow) {
   add_Little_More_Spice();
}
catch(AddOnsException e) {
  ignore_Additional_Flavors_If_Not_Available();
}
catch(Exception e) {
  notListedIssue();
}
Finally {
  cleanUp_Kitchen();
}

Here there could be more catches for one try as one task may encounter many different issues. If it is solvable its called exception and we try to catch in catch blocks. The JVM process our code (cookingProcess) and if it encounter one problem like QtyException_Spice, it will throw the appropriate object. Then it will be caught by the corresponding catch, which will execute add_Little_More_Spice() and prevent the code from failing.

Here we see one more word, Exception, which is the parent class of all exceptions. Sometimes we may encounter the issue that is not listed (perhaps forgotten) but its solvable. In such cases, we can use the parent class object (since a parent class object can act as a child object) to catch any exception that is not listed.

Fine, all good. But what is the purpose of Finally here? Finally is the block of code that will always be executed, no matter if exception occurs or not. It doesn’t matter if you made a good dish or a bad one, but the kitchen must be cleaned. The same applies here: the finally block is used for releasing system resources that were mainly used (Ex. File). However, we can also write our own code in the finally block based on the specific requirements.

We have a situation where you have one cylinder to cook, and it gets emptied during cooking, so we cannot proceed. This will fail our process TastyDish, this situation cannot be handled immediately. This is called Error. Now lets recall the definition β€œErrors are serious issues that are beyond our control like a system crash or resource limitations.” Now we could understand, right?

Ex. OutOfMemoryError – when we load too much data, JVM runs out of memory. StackOverFlowError – when an infinite loop or recursion without base condition will make the stack overflow.

Lets revisit exceptions – they can be classified into two categories:

  • Checked Exception
  • UnChecked Exception.

What is Checked Exceptions?

Checked Exception is the exception which occurs at compile time. It will not allow you to run the code if you are not handling through try-catch or declares throws method.

Lets get into deeper for the clear understanding, the compiler predicts/doubts the part of our code which may throw the exceptions/mistakes which lead to stopping the execution. So that it will not allow you to run, it is forcing you to catch the exception through the above one of mechanisms.

If it is not clear, let us take an example, in the above code we have VesselException and QtyException_Spice . You are at your initial stage of cooking under the supervision of your parent. So we are ordered/ instructed to keep the big vessel and the spices nearby in case you may need it when the problem arise. If you are not keeping it nearby parent is not allowing you to start cooking (initial time ). Parent is compiler here.

throws:

So Expected exception by the compiler is called Checked Exception, and the compiler force us to handle. One solution we know try-catch-finally, what is that through declaration in the method? The exception in which method can be expected, that method should use the keyword β€œthrows <ExceptionClassName-1>” that is, it specifies this method may lead to the exceptions from the list of classes specified after throws keyword. After throws can be one class or more than one. whoever using this method with this declaration in method signature will aware of that and may handle it.

The good example for this is, IOException (parent) – FileNotFoundException (child). If you are trying to open a file, read it, the possible exceptions are: File Path Incorrect, File doesn’t exist, File Permission, Network issues etc. For Ex.

public static void main(String[] args) {
        try {
            // Calling the method that may throw a FileNotFoundException
            readFile("nonexistentfile.txt");
        } catch (FileNotFoundException e) {
            // Handle exception here
            System.out.println("File not found! Please check the file path.");
            e.printStackTrace();
        }
    }   

 // Method that throws FileNotFoundException
    public static void readFile(String fileName) throws FileNotFoundException {
        File file = new File(fileName);
        Scanner scanner = new Scanner(file);  // This line may throw FileNotFoundException
        while (scanner.hasNextLine()) {
            System.out.println(scanner.nextLine());
        }
        scanner.close();
    }

What is Unchecked Exception?

The compiler will not alert you about this exception, instead you will experience at runtime only. This not required to be declared or caught, but handling is advisable. These are all subclasses of RunTimeException (Error also will throw runtime exception only). It could be thrown when runtime issues, illegal arguments, or programming issues.

Ex.Invalid index in an array, or trying to take value from a null object, or dividing by zero.

Ex. NullPointerException

String str = null; System.out.println(str.length()); /* Throws NullPointerException */

ArrayIndexOutOfBoundsException

int[] arr = new int[3]; System.out.println(arr[5]); /* Throws ArrayIndexOutOfBoundsException */

What is throw?

Instead JRE throws error, the developer can throw the exception object (Predefined or UserDefined) to signal some erroneous situation and wants to stop the execution. For ex, you have the idea of wrong input and wants to give your own error message.

public class SampleOfThrow {
    public static void main(String[] args) {
        // a/b --> b should not be 0
        Scanner scn = new Scanner(System.in);
        int a = scn.nextInt();
        int b = scn.nextInt();
        if (b==0) throw new ArithmeticException("b value could not be zero");
        System.out.print(a/b);
    }
}

Hey, wait, I read the word, User Defined Exception above. which means the developer (we) also can create our own exception and can throw it. Yes, absolutely. How? In Java everything is class, right? So through class only, but on one condition it should extend the parent Exception class in order to specify it is an exception.

//User Defined Exception
class UsDef extends Exception {
    public UsDef(String message) {
        super(message); //will call Exception class // and send the own error message
    }
}

public class MainClass {
    public static void main(String[] args) {
        try {
            Scanner scn = new Scanner(System.in);
            boolean moreSalt = scn.nextBoolean(); 
            validateFood(moreSalt);
 // This method will throw an TooMuchSaltException
        } catch (TooMuchSaltException e) {
            System.out.println(e.getMessage());  // Catching and handling the custom exception
        }
    }

    // Method that throws TooMuchSaltException if food contains too much salt and can't eat
    public static void validateFood(boolean moreSalt) throws TooMuchSaltException {
        if (moreSalt) {
            throw new TooMuchSaltException("Food is too salty.");
        }
        System.out.println("Salt is in correct quantity");
    }
}

Now Lets have a look at some important Exception Handling points in java of view. (The following are taken from chatGPT)

Error Vs. Exception

AspectErrorException
DefinitionAn Error represents a serious problem that a Java application cannot reasonably recover from. These are usually related to the Java runtime environment or the system.An Exception represents conditions that can be handled or recovered from during the application’s execution, usually due to issues in the program’s logic or input.
Superclassjava.lang.Errorjava.lang.Exception
RecoveryErrors usually cannot be recovered from, and it is generally not advisable to catch them.Exceptions can typically be caught and handled by the program to allow for recovery or graceful failure.
Common TypesOutOfMemoryError, StackOverflowError, VirtualMachineError, InternalErrorIOException, SQLException, NullPointerException, IllegalArgumentException, FileNotFoundException
Occurs Due ToTypically caused by severe issues like running out of memory, system failures, or hardware errors.Typically caused by program bugs or invalid operations, such as accessing null objects, dividing by zero, or invalid user input.
Checked or UncheckedAlways unchecked (extends Throwable but not Exception).Checked exceptions extend Exception or unchecked exceptions extend RuntimeException.
Examples– OutOfMemoryError
– StackOverflowError
– VirtualMachineError
– IOException
– SQLException
– NullPointerException
– ArithmeticException
HandlingErrors are usually not handled explicitly by the program. They indicate fatal problems.Exceptions can and should be handled, either by the program or by throwing them to the calling method.
PurposeErrors are used to indicate severe problems that are typically out of the program’s control.Exceptions are used to handle exceptional conditions that can be anticipated and managed in the program.
Examples of Causes– System crash
– Exhaustion of JVM resources (e.g., memory)
– Hardware failure
– File not found
– Invalid input
– Network issues
ThrowingYou generally should not throw Error explicitly. These are thrown by the JVM when something critical happens.You can explicitly throw exceptions using the throw keyword, especially for custom exceptions.

Checked vs. Unchecked Exception:

AspectChecked ExceptionUnchecked Exception
DefinitionExceptions that are explicitly checked by the compiler at compile time.Exceptions that are not checked by the compiler, and are typically runtime exceptions.
SuperclassSubclasses of Exception but not RuntimeException.Subclasses of RuntimeException.
Handling RequirementMust be caught or declared in the method signature using throws.No explicit handling required; they can be left uncaught.
ExamplesIOException, SQLException, ClassNotFoundException.NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException.
Common UsageTypically used for exceptional conditions that a program might want to recover from.Used for programming errors or unforeseen runtime issues.
Checked atCompile-time.Runtime (execution time).
Effect on CodeForces the developer to handle the exception (either with a try-catch or throws).No such requirement; can be ignored without compiler errors.
Examples of CausesMissing file, network failure, database errors.Null pointer dereference, dividing by zero, illegal array index access.
When to UseWhen recovery from the exception is possible or expected.When the error typically indicates a bug or programming mistake that cannot be recovered from.

throw vs. throws:

Aspectthrowthrows
DefinitionUsed to explicitly throw an exception from a method or block of code.Used in a method signature to declare that a method can throw one or more exceptions.
UsageUsed with an actual exception object to initiate the throwing of an exception.Used in the method header to inform the compiler and the caller that the method might throw specific exceptions.
Keyword TypeStatement (flow control keyword).Modifier (appears in the method declaration).
Examplethrow new IOException("File not found");public void readFile() throws IOException { ... }
LocationCan be used anywhere inside the method or block to throw an exception.Appears only in the method signature, usually right after the method name.
ControlImmediately transfers control to the nearest catch block or exits the program if uncaught.Allows a method to propagate the exception up the call stack to the caller, who must handle it.
Checked vs UncheckedCan throw both checked and unchecked exceptions.Typically used for checked exceptions (like IOException, SQLException) but can also be used for unchecked exceptions.
Example ScenarioYou encounter an error condition, and you want to throw an exception.You are writing a method that may encounter an error (like file I/O) and want to pass the responsibility for handling the exception to the caller.

References : 1. https://www.geeksforgeeks.org/exceptions-in-java/

❌