6

通常在编写公共方法时,我会进行一些错误检查,例如

public SomeResult processSomething (int i, List<String> items) {
   if( i < 0 ) {
      throw new IllegalArgumentException();
   }
  if(items == null) {
     throw new NullPointerException();
  }
etc
}

在android编程中,标准方法是什么?我注意到当一个片段崩溃时,模拟器会转到前一个片段,所以从向用户显示的行为来看,我猜它是可以的。但是处理异常/错误情况的最佳方法是什么?

4

2 回答 2

2

这里的最佳实践与 Java 世界其他地方使用的非常相似:

1.方法的第一行通常专门用于检查方法参数的有效性。如果发生错误,该方法应尽快失败。

验证参数时,Exception如果测试失败,则抛出 an。它通常是抛出的这些未经检查的异常之一:

  • IllegalArgumentException
  • NullPointerException
  • IllegalStateException

这些都来源于RuntimeException.

2.如果一个类中每个方法的每个对象参数都需要非空以避免抛出,那么可以在通用类中声明一次,而不是为每个方法重复。NullPointerExceptionjavadoc

参考:

前置条件、后置条件和类不变量

编辑:

回答您关于“查看特定错误”的问题:虽然可以这样做,但其想法是Exception表明代码中存在编程错误。因此,应允许应用程序崩溃,以便用户可以报告错误,从而开发人员从应用程序的 Play 商店帐户中获取错误日志。这样他就可以纠正这些错误的根源。这个过程应该一直持续到,假设应用程序完全没有错误。

于 2015-03-22T11:44:33.590 回答
1

现在我们可以使用Kotlin Preconditions.kt

data class User(val active: Boolean, val email: String?)

class UserHelper (private val user: User) {

    fun mergeUsers(otherUser: User) {
        // To verify enclosing class state we use "check methods".
        // If check fails IllegalStateException will be thrown
        checkNotNull(user.email) { "user email is null" }
        check(user.active) { "user is not active" }

        // To verify argument we use "require methods".
        // If check fails IllegalArgumentException will be thrown
        requireNotNull(otherUser.email) { "otherUser email is null" }
        require(otherUser.active) { "otherUser is not active" }

        // All the preconditions has been meet, so we can merge users
        // ...
    }
}
于 2020-04-10T10:27:11.257 回答