我为什么要关心 Java 中捕获的异常?

Why should I care about caught exceptions in Java?

我曾多次注意到,在 Eclipse 和 Android Studio 中启用异常断点默认选中 "Caught exceptions" 复选框。有什么理由让我选中它吗?

为什么我要关心 Java 中捕获的异常?

异常会在您的代码或逻辑出现问题时为您提供帮助。您可以使用异常,而不是使用 ifelse 语句来处理错误,这需要编写更多代码并且代码本身可能会在过程中中断。异常允许您像往常一样编写代码并通过添加 trycatchfinally 块来处理它们。然后程序将使用异常来指示发生错误。

  • try 是可能发生异常的代码块,它应该 包含至少一个捕获(或多个),或 finally 块。
  • catch 是将处理特定类型异常的代码块。
  • finally是保证在之后执行的代码块 try 块。

"To throw an exception, use the throw statement and provide it with an exception object — a descendant of Throwable — to provide information about the specific error that occurred. A method that throws an uncaught, checked exception must include a throws clause in its declaration." - 来自异常 Oracle 文档

Exceptions 对象有更多关于它抛出的错误的信息。 "With the exception chaining, an exception can point to the exception that caused it, which can in turn point to the exception that caused it, and so on." - 来自异常 Oracle 文档

我曾多次注意到,在 Eclipse 和 Android Studio 中启用异常断点默认选中 "Caught exceptions" 框。有什么理由让我选中它吗?

如果您希望在抛出异常时暂停执行并使用 catch 子句捕获异常,则使用捕获异常复选框。

Android

Android 异常与 java 几乎相同。但是,在 Android 中没有控制台,因此您必须向用户报告异常。向用户显示异常的方式是在 toast 或对话框中。

您可以在此处获取有关异常的更多信息: https://docs.oracle.com/javase/tutorial/essential/exceptions/ http://www.javacodegeeks.com/2013/07/java-exception-handling-tutorial-with-examples-and-best-practices.html https://androidcookbook.com/Recipe.seam;jsessionid=ED0972E495383DBA84BE448E717BB749?recipeId=75&recipeFrom=ViewTOC