Passing Exception to custom Exception Handler Method. Java

Tobyrrr00 :

I have a class with about 20 methods which all catch 1 or more Exceptions and then respond to the user based on that Exception. Instead of writing them over and over again, I want to create a single method which is passed the Exception, handles it, and gives the appropriate response.

Here's an example

public boolean addFirst(Object data){

    try {
        //add something 
        return true;
    } catch(Exception e) {
        exceptionHandler(e);
        return false;
    } 
}

But when I try to compare it with "e" it gives me "Exception cannot be resolved to a variable".

private void exceptionHandler(Exception e) {
    if(e == UnsupportedOperationException) {
        System.out.println("Operation is not supported.");
    } else if (e == ClassCastException) {
        System.out.println("Class of the specified element prevents it from being added to this list.");
    } else if (e == NullPointerException) {
        System.out.println("You cannot enter nothing.");
    } else if (e == IndexOutOfBoundsException) {
        System.out.println("Your specified index is larger than the size of the LinkedList. Please choose a lower value.");
    } else if(e == Exception) {
        System.out.println("You messed up so hard that I don't even know what you did wrong."); 
    }
}
akuzminykh :

E.g. UnsupportedOperationException is not a declared variable, this is what the compiler is complaining about.

When doing e == UnsupportedOperationException you are checking if the reference of e equals the reference of UnsupportedOperationException but UnsupportedOperationException was never declared.

To check the type of an object you have to use the instanceof keyword and the class you want to check against.

e instanceof UnsupportedOperationException

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=296158&siteId=1