gpt4 book ai didi

java - java中最常用的运行时异常有哪些?

转载 作者:IT老高 更新时间:2023-10-28 20:39:48 32 4
gpt4 key购买 nike

作为一名希望完善自己的编程技能的 java 程序员,我经常遇到必须创建运行时异常的情况。我知道如果明智地使用它是一种很好的做法。

就我个人而言,NullPointerExceptionIllegalStateException 是我创建的软件中最常用的。你呢?

您经常使用哪些运行时异常?你在什么情况下使用它们?

最佳答案

我从不抛出 NullPointerException。对我来说,当出现问题时,它会自然地出现在代码中,这需要开发人员查看会发生什么。然后他(s)修复了原因,并且不再发生。

我使用 IllegalStateException 来表示对象配置不正确或调用顺序不正确。但是,我们都知道,理想情况下,一个对象应该确保它不会处于错误状态,并且您不能以错误的顺序调用它(创建一个构建器和一个结果对象......)。

当一个方法检测到它的参数不正确时,我会使用很多 IllegalArgumentException。这是任何公共(public)方法的责任,停止处理(以避免更难以理解的间接错误)。此外,方法开头的一些 if 用于文档目的(文档永远不会偏离代码,因为它是代码 :-))。

     public void myMethod(String message, Long id) {
if (message == null) {
throw new IllegalArgumentException("myMethod's message can't be null");
// The message doesn't log the argument because we know its value, it is null.
}
if (id == null) {
throw new IllegalArgumentException("myMethod's id can't be null");
// This case is separated from the previous one for two reasons :
// 1. to output a precise message
// 2. to document clearly in the code the requirements
}
if (message.length()<12) {
throw new IllegalArgumentException("myMethod's message is too small, was '" + message + "'");
// here, we need to output the message itself,
// because it is a useful debug information.
}
}

我还使用特定的运行时异常来表示更高级别的异常情况。

For example, if a module of my application couldn't start, I might have a ModuleNotOperationalException thrown (ideally by a generic code like an interceptor, otherwise by a specific code) when another module calls it. After that architectural decision, each module has to deal with this exception on operations that call other modules...

关于java - java中最常用的运行时异常有哪些?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1502860/

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