gpt4 book ai didi

java - 为什么调用函数时需要 "throws Exception"?

转载 作者:IT老高 更新时间:2023-10-28 11:39:14 26 4
gpt4 key购买 nike

class throwseg1
{
void show() throws Exception
{
throw new Exception("my.own.Exception");
}

void show2() throws Exception // Why throws is necessary here ?
{
show();
}

void show3() throws Exception // Why throws is necessary here ?
{
show2();
}

public static void main(String s[]) throws Exception // Why throws is necessary here ?
{
throwseg1 o1 = new throwseg1();
o1.show3();
}
}

为什么编译器报告方法 show2()show3()main()

unreported exception Exception that must be caught or declared to be thrown

当我从这些方法中删除 throws Exception 时?

最佳答案

您可能知道,在 Java 中,异常可以分为两种:一种需要 throws 子句,或者如果您不指定则必须处理,另一种则不需要。现在,看下图:

enter image description here

在 Java 中,您可以抛出任何扩展 Throwable 类的东西。但是,您不需要为所有类指定 throws 子句。具体来说,是 ErrorRuntimeException 或这两者的任何子类的类。在您的情况下,Exception 不是 ErrorRuntimeException 的子类。因此,这是一个检查异常,如果您不处理该特定异常,则必须在 throws 子句中指定。这就是您需要 throws 子句的原因。


来自 Java Tutorial :

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

现在,如您所知,异常分为两种:已检查和未检查。为什么要进行这些分类?

Checked Exception:它们用于表示在程序执行过程中可以恢复的问题。它们通常不是程序员的错。例如,用户指定的文件不可读,或没有可用的网络连接等,在所有这些情况下,我们的程序都不需要退出,而是可以采取诸如警告用户之类的操作,或者进入回退机制(如网络不可用时离线工作)等。

Unchecked Exceptions: 它们又可以分为两种:Errors 和 RuntimeExceptions。不检查它们的一个原因是它们数量众多,并且需要处理所有这些会使我们的程序困惑并降低其清晰度。另一个原因是:

  • 运行时异常:它们通常是由于程序员的错误而发生的。例如,如果出现被零除的ArithmeticExceptionArrayIndexOutOfBoundsException,那是因为我们编码不够仔细。它们的发生通常是因为我们的程序逻辑中的一些错误。因此,必须在我们的程序进入生产模式之前清除它们。它们是未经检查的,因为我们的程序在发生时必须失败,以便我们程序员可以在开发和测试时自行解决它。

  • 错误:错误是程序通常无法恢复的情况。例如,如果发生StackOverflowError,我们的程序就不能做很多事情,比如增加程序的函数调用堆栈的大小。或者,如果发生 OutOfMemoryError,我们就无法增加程序可用的 RAM 量。在这种情况下,最好退出程序。这就是为什么它们不被选中。

详细信息见:

关于java - 为什么调用函数时需要 "throws Exception"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11589302/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com