在 Java/Android 中抛出自定义异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28693363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:38:52  来源:igfitidea点击:

Throw custom Exceptions in Java/Android

javaandroidexceptionexception-handling

提问by Sonhja

I'm developing a custom Exception class, in which I have the following constructors:

我正在开发一个自定义 Exception 类,其中有以下构造函数:

public class UserException extends Exception
{
    string message;
    public UserException() {
        super();
    }

    public UserException(String message, Throwable cause)
    {
        super(message, cause);

        this.cause = cause;
        this.message = message;
    }
}

And I create a new custom exception like this:

我创建了一个新的自定义异常,如下所示:

private Camera.PreviewCallback SetPreviewCallBack() throws UserException {
    .......
    // Something went wrong
    throw new UserException("Something failed.", new Throwable(String.valueOf(UserExceptionType.CaptureFailed)));
 }

But when I insert my throw new UserException(...)it tells me to surround it with try/catch!! That's not the idea, isn't it? I want to throw custom exceptions when I need them to be thrown, without surronding my new Exceptionswith more try/catchclauses.

但是当我插入throw new UserException(...)它时,它告诉我用try/catch!! 不是这个想法,不是吗?我想在需要抛出自定义异常时抛出它们,而不用new Exceptions更多的try/catch子句包围我。

So, what I'm doing wrong? What I'm misunderstanding?

那么,我做错了什么?我误会了什么?

采纳答案by DennisW

In addition to Eran's answer, you could also make your custom Exception extend RuntimeException, which does not need to be caught.

除了 Eran 的回答之外,您还可以让您的自定义 Exception 扩展RuntimeException,这不需要被捕获。

回答by Eran

If the method that throws this exception doesn't handle it (i.e. it doesn't catch it), it must declare it in the throwsclause, since this is a checked exception.

如果抛出这个异常的方法没有处理它(即它没有捕获它),它必须在throws子句中声明它,因为这是一个已检查的异常。

public void yourMethod () throws UserException
{
    ...
    throw new UserException("Something failed.", new Throwable(String.valueOf(UserExceptionType.CaptureFailed)));
    ...
}

回答by Ankit

if your Custom Exception extends from Exceptionclass, it must be handled (using try-catch) or passed on to caller (using throws). If you just want to leave it to runtime to handle the exception, You need to extend it from RuntimeExceptionClass Since its the 1st case in your scenario, You should do something like this:

如果您的自定义异常从Exception类扩展,则必须对其进行处理(使用try-catch)或传递给调用者(使用throws)。如果您只想让它运行时处理异常,您需要从RuntimeExceptionClass扩展它,因为它是您场景中的第一种情况,您应该执行以下操作:

public void surroundingMethod() throws UserException{
    throw new UserException("Something failed.", new Throwable(String.valueOf(UserExceptionType.CaptureFailed)));
}

this will essentially pass your exception to the caller, so now it will be caller's responsibility to handle it with try-catch or pass it on again.

这基本上会将您的异常传递给调用者,因此现在调用者有责任使用 try-catch 处理它或再次传递它。

so again, u need to modify calling instruction as

所以再次,你需要修改调用指令为

public void callingMethod () {
    try {
        surroundingMethod();
    } catch (UserException ex){
    }
}

回答by amit

You should either declare your methods as throws UserException- or make your exception extend RuntimeException.

您应该将您的方法声明为throws UserException- 或使您的异常扩展RuntimeException

The later is officially unadvised, but is often used to bypass the java's declared exception mechanism.

后者是官方不建议的,但通常用于绕过java 声明的异常机制

回答by Y.S

In Java, when you throwa checkedException, there is one more thing you are required to do:

在Java中,当你throw检查Exception,有您需要做的一两件事:

1.Either add a try-catchblock around the throwand handle this Exceptionwithin the same method.

1.try-catch在 周围添加一个块throwException在同一方法中处理它。

2.Or add a throwsstatement to the method definition, transferring the responsibility for the handling of the the Exceptionto a higher-level method.

2.或者throws在方法定义中添加一条语句,将处理 的责任转移Exception到更高级别的方法。

This is part of the overall OOP paradigms of modularity & abstraction: who is responsible for handling an Exception, the caller of a method or the method itself ? The answer depends on the nature of the Exception.

这是模块化和抽象的整体 OOP 范式的一部分:谁负责处理Exception,是方法的调用者还是方法本身?答案取决于Exception.