gpt4 book ai didi

java - 为什么没有 try catch block 来调用 static void main()

转载 作者:太空宇宙 更新时间:2023-11-04 06:13:31 24 4
gpt4 key购买 nike

当我浏览JLS 8 11.2时我发现了以下规则:

The Java programming language requires that a program contains handlers for checked exceptions which can result from execution of a method or constructor (§8.4.6, §8.8.5). This compile-time checking for the presence of exception handlers is designed to reduce the number of exceptions which are not properly handled. For each checked exception which is a possible result, the throws clause for the method or constructor must mention the class of that exception or one of the superclasses of the class of that exception (§11.2.3).

我无法理解该规则的意义。例如,我知道这两个程序

class Main
{
public static void main (String[] args) throws Exception
{
throw new Exception();
}
}

DEMO

class Main
{
public static void main (String[] args) throws Exception
{
try{
throw new Exception();
} catch (Expection e){ }
}
}

DEMO

结构良好。

但是该规则要求程序包含针对第一个不正确的任何已检查异常的处理程序。其实看看handler的定义:

Every exception is represented by an instance of the class Throwable or one of its subclasses (§11.1). Such an object can be used to carry information from the point at which an exception occurs to the handler that catches it. Handlers are established by catch clauses of try statements (§14.20).

强调我的。

因此,在第一个程序中,除了

之外没有任何处理程序

The Java programming language requires that a program contains handlers for checked exceptions

你不能澄清一下这个规则吗?

最佳答案

How does the JVM handle an exception thrown by the main method对此进行了详细介绍。 。

本质上,这是由 JVM 内部完成的 - 因此不受任何 JLS 规则的约束。如果您愿意,您可以覆盖此行为。

public static void main(String[] args) throws Exception {
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("I caught it !" + e);
}
});
throw new Exception();
}

除了JLS execution chapter之外,我找不到任何正式的规范。仅涵盖 main() 的定义。它可能不存在,并不是世界上所有的地方都有很好的记录。 The c code对于java运行器使用JNI。这应该会让您了解发生了什么以及为什么 JLS 在这里无关紧要。

/* Build argument array */
mainArgs = NewPlatformStringArray(env, argv, argc);
if (mainArgs == NULL) {
ReportExceptionDescription(env);
goto leave;
}

/* Invoke main method. */
(*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);

/*
* The launcher's exit code (in the absence of calls to
* System.exit) will be non-zero if main threw an exception.
*/
ret = (*env)->ExceptionOccurred(env) == NULL ? 0 : 1;

关于java - 为什么没有 try catch block 来调用 static void main(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28391472/

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