是否可以告诉编译器方法总是抛出异常 [英] Is it possible to tell the compiler that a method always throws an Exception

查看:114
本文介绍了是否可以告诉编译器方法总是抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般来说,Java编译器不会传播方法总是抛出异常的信息,因此不会检测到所有代码路径都已完成。

Generally speaking, the Java compiler does not propagate the information that a method "always" throw an Exception, and therefore, does not detect that all code paths are complete.

(这是因为Java编译器独立编译每个类)。

(This is due to the fact that Java compiler compiles each class independently).

当你想写这样的东西时,这是一个问题。

It's a problem when you want to write something like that.

public class ErrorContext {
    public void fatalISE(String message) {
        String context = "gather lots of information about the context of the error";
        throw new IllegalStateException(context +": " + message);
    }
}

public class A {
    public MyObject myMethod() {
        if (allIsGood()) {
            return new MyObject();
        }
        ErrorContext.fatalISE("all is not good");
    }
}

(即一种断言助手,收集上下文信息)。

(ie, a kind of "assertion helper" that gathers context information).

因为编译器会抱怨myMethod并不总是返回MyObject。

Because the compiler will complain that myMethod does not always return a MyObject.

To我的知识,没有特定的注释来指示方法总是抛出。

To my knowledge, there is no specific annotation to indicate that a method always throws.

推荐答案

一个简单的解决方法是让你的 fatalISE 方法不抛出异常,但只创建它:

A simple workaround is to let your fatalISE method not throw the exception, but only create it:

public class ErrorContext {
    public IllegalStateException fatalISE(String message) {
        String context = "gather lots of information about the context of the error";
        return new IllegalStateException(context +": " + message);
    }
}

public class A {
    public MyObject myMethod() {
        if (allIsGood()) {
            return new MyObject();
        }
        throw ErrorContext.fatalISE("all is not good");
    }
}

这样编译器就会知道不要抱怨缺少返回。并且忘记使用 throw 是不太可能的,因为编译器通常会抱怨。

This way the compiler will know not to complain about a missing return. And forgetting to use the throw is unlikely, exactly because the compiler will usually complain.

这篇关于是否可以告诉编译器方法总是抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆