将异常传递给自定义异常处理程序方法。爪哇

时间:2020-03-17 05:50:04

标签: java exception methods parameter-passing

我有一个包含大约20个方法的类,这些方法都捕获1个或更多异常,然后根据该异常响应用户。我不想一遍又一遍地编写它们,我想创建一个传递异常,对其进行处理并给出适当响应的方法。

这是一个例子

public boolean addFirst(Object data){

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

但是当我尝试将其与“ e”进行比较时,它给出了“ Exception 无法解析为变量”。

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."); 
    }
}

2 个答案:

答案 0 :(得分:1)

您将要使用instanceof而不是==,因为您正在尝试比较两种不同的类型。

if(e instanceof UnsupportedOperationException)

答案 1 :(得分:1)

例如(ediff)不是声明的变量,这是编译器抱怨的。

执行<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> 时,您要检查UnsupportedOperationException的引用是否等于e == UnsupportedOperationException的引用,但从未声明e

要检查对象的类型,必须使用UnsupportedOperationException关键字和要检查的UnsupportedOperationException

instanceof
相关问题