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

本文探讨了作为一名Java程序员在编程中如何明智地使用运行时异常,特别是NullPointerException和IllegalStateException。作者指出,不主动抛出NullPointerException,而让其自然出现以帮助开发者定位问题。IllegalStateException用于指示对象配置错误或调用顺序不正确。此外,IllegalArgumentException用于检查方法参数的正确性。最后,特定的RuntimeException用于表示更高层次的异常情况,例如模块启动失败。

As a java programmer who wishes to perfect his programming skills, I often come across the situations that I have to create a runtime exception. I know it's a good practice if one use wisely.

Personally, NullPointerException and IllegalStateException are the most commonly used in the softwares that I have created. How about you?

What runtime exceptions do you often use? In what situations do you use them?

解决方案

I never throw NullPointerException. For me, it is one that appears naturally in the code when something goes wrong and that requires a developer to look at what happens. Then (s)he fixes the cause and it doesn't happen again.

I use IllegalStateException to signal that an object is incorrectly configured or that calls are in an incorrect order. However, we all know that ideally, an object should ensure it can't be in a bad state and that you can't call it in incorrect order (make a builder and a resulting object ...).

I use a lot of IllegalArgumentException when a method detects that its parameters are incorrect. This is the responsibility of any public method, to stop processing (to avoid indirect errors that are more difficult to understand). Also, a few ifs in the beginning of a method serve a documentation purpose (documentation that never diverge from the code because it is the code :-) ).

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.

}

}

I also use specific Runtime Exceptions to signal higher level exceptional conditions.

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、付费专栏及课程。

余额充值