java中什么是运行异常_在java中最常用的运行时异常是什么?

我从不会抛出NullPointerException。对我来说,它是一个出现在代码中当出现问题时,需要开发人员看看会发生什么。然后(s)他固定的原因,它不会再次发生。

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

当一个方法检测到其参数不正确时,我使用了很多IllegalArgumentException。这是任何公共方法的责任,停止处理(以避免更难以理解的间接错误)。另外,在方法开始的几个ifs提供文档目的(文档从不偏离代码,因为它是代码:-))。

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…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值