我有一个永远不会返回的 Android 错误处理程序(它记录一条消息并引发错误异常)。如果我从通常返回值的方法调用错误处理程序,Android Studio lint 检查器会报告错误,因为没有返回值。有没有办法告诉 Android Studio 我的错误处理程序没有返回,或者在调用它之后代码中的点实际上是无法访问的。
当然,我可以放入一个不必要的 return 语句,返回一个正确类型的虚拟值,但这是不雅的,并且用无法访问的语句使我的应用程序混乱。
我找不到要禁用的代码检查以防止错误,但即使有一个要禁用,也会阻止它报告真正缺少的返回语句。
再说一遍,这不是Java 语法问题。人们说过,Java 方法必须返回声明类型的值。这是
(a)不相关的
(b)不正确的。
正确的说法是,如果 Java 方法返回,则必须返回声明类型的值。这段代码
public long getUnsignedLong(String columnName)
throws NumberFormatException, NoColumnException
{
String s = getString(columnName, "getUnsignedLong");
if ((s != null) && s.matches("^[0-9]+$")) {
return Long.parseLong(s);
}
else
{
throw(new NumberFormatException("Bad number " + s));
}
}
是完全有效的 Java,AS 不会抱怨它。return
确实,如果我像这样插入不必要的
public long getUnsignedLong(String columnName)
throws NumberFormatException, NoColumnException
{
String s = getString(columnName, "getUnsignedLong");
if ((s != null) && s.matches("^[0-9]+$")) {
return Long.parseLong(s);
}
else
{
throw(new NumberFormatException("Bad number " + s));
}
return 0;
}
AS 抱怨它无法访问。
我抛出异常的问题是,如果它真的发生了,我的应用程序的用户看到的是一个弹出窗口,提示应用程序已停止并询问用户是否要禁用它。这对用户不是很有帮助,当用户向我报告它已经发生时,对我也不是很有帮助。因此,我没有抛出异常,而是调用了我的致命错误处理程序,如下所示:-
// Always invoked with fatal = true
// Report a fatal error.
// We send a message to the log file (if logging is enabled).
// If this thread is the UI thread, we display a Toast:
// otherwise we show a notification.
// Then we throw an Error exception which will cause Android to
// terminate the thread and display a (not so helpful) message.
public MyLog(Context context, boolean fatal, String small, String big) {
new Notifier(context, small, big);
new MyLog(context, big, false);
throw(new Error());
}
是的,我知道这个参数fatal
没有被引用,但是它的存在安排了我的错误处理程序的这个特殊重载被调用,你可以看到它抛出一个异常并且不返回。
我的实际问题是,如果我通过调用不返回的致命错误处理程序来替换throw
in ,则 AS 在结束时抱怨它返回时没有值。好吧,这是错误的:这一点与以前一样不可触及。我尝试在说它总是失败之前放置一个合同,但这没有帮助,并且在 AS 错误报告中按右箭头并没有提供任何抑制它的方法。我可以输入一个 dummy statement 或一个 dummy ,但其中任何一个实际上都是无法访问的代码,我认为这是不优雅和不必要的。getUnsignedLong
getUnsignedLong
MyLog
return
throw
所以我的问题与最初提出的问题一样:我如何告诉 Android Studio 一个方法没有返回?