我已经在StackOverFlow上阅读了有关已检查和未经检查的异常的多个帖子.老实说,我还是不太确定如何正确使用它们.
Joshua Bloch在" Effective Java "中说过
对可恢复条件使用已检查的异常,对编程错误使用运行时异常(第2版中的第58项)
让我们看看我是否正确理解这一点.
以下是我对已检查异常的理解:
try{
String userInput = //read in user input
Long id = Long.parseLong(userInput);
}catch(NumberFormatException e){
id = 0; //recover the situation by setting the id to 0
}
Run Code Online (Sandbox Code Playgroud)
1.以上是否考虑了检查异常?
2. RuntimeException是未经检查的异常吗?
以下是我对未经检查的异常的理解:
try{
File file = new File("my/file/path");
FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){
//3. What should I do here?
//Should I "throw new FileNotFoundException("File not found");"?
//Should I log?
//Or should I System.exit(0);?
}
Run Code Online (Sandbox Code Playgroud)
4.现在,上述代码也不能成为检查异常吗?我可以尝试恢复这样的情况吗?我可以吗?(注意:我的第3个问题在catch上面)
try{
String …Run Code Online (Sandbox Code Playgroud) java exception runtimeexception checked-exceptions unchecked-exception
可能重复:
何时选择已检查和未检查的异常
我应该何时创建一个已检查的异常,何时应该生成运行时异常?
例如,假设我创建了以下类:
public class Account {
private float balance;
/* ... constructor, getter, and other fields and methods */
public void transferTo(Account other, float amount) {
if (amount > balance)
throw new NotEnoughBalanceException();
/* ... */
}
}
Run Code Online (Sandbox Code Playgroud)
我应该如何创建我的NotEnoughBalanceException?它应该延伸Exception还是RuntimeException?或者我应该使用IllegalArgumentException?
我正在使用Java 8中的新lambda特性,并发现Java 8提供的实践非常有用.但是,我想知道是否有一种很好的方法可以解决以下情况.假设您有一个对象池包装器,需要某种工厂来填充对象池,例如(使用java.lang.functions.Factory):
public class JdbcConnectionPool extends ObjectPool<Connection> {
public ConnectionPool(int maxConnections, String url) {
super(new Factory<Connection>() {
@Override
public Connection make() {
try {
return DriverManager.getConnection(url);
} catch ( SQLException ex ) {
throw new RuntimeException(ex);
}
}
}, maxConnections);
}
}
Run Code Online (Sandbox Code Playgroud)
将函数接口转换为lambda表达式后,上面的代码变为:
public class JdbcConnectionPool extends ObjectPool<Connection> {
public ConnectionPool(int maxConnections, String url) {
super(() -> {
try {
return DriverManager.getConnection(url);
} catch ( SQLException ex ) {
throw new RuntimeException(ex);
}
}, maxConnections); …Run Code Online (Sandbox Code Playgroud) 我有以下课程.
public class ValidationException extends RuntimeException {
}
Run Code Online (Sandbox Code Playgroud)
和
public class ValidationException extends Exception {
}
Run Code Online (Sandbox Code Playgroud)
我很困惑自定义异常何时应该扩展RunTimeException以及什么时候必须扩展Exception.能否请您解释一下我是否有RunTimeException直接延伸的缺点?
谢谢!
考虑:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.io.*;
public class EncryptURL extends JApplet implements ActionListener {
Container content;
JTextField userName = new JTextField();
JTextField firstName = new JTextField();
JTextField lastName = new JTextField();
JTextField email = new JTextField();
JTextField phone = new JTextField();
JTextField heartbeatID = new JTextField();
JTextField regionCode = new JTextField();
JTextField retRegionCode = new JTextField();
JTextField encryptedTextField = new JTextField();
JPanel finishPanel = new JPanel();
public void init() {
//setTitle("Book …Run Code Online (Sandbox Code Playgroud) 这是代码:
public Response getABC(Request request) throws Exception {
Response res = new Response();
try {
if (request.someProperty == 1) {
// business logic
} else {
throw new Exception("xxxx");
}
} catch (Exception e) {
res.setMessage(e.getMessage); // I think this is weird
}
return res;
}
Run Code Online (Sandbox Code Playgroud)
这个程序运行正常.我认为它应该重新设计,但如何?
我正在编写一个使用的程序java.net.URLDecoder.decode(String value, String encoding).显然,这种方法可能会抛出一个UnsupportedEncodingException,我得到了.但我只是传递"UTF-8"作为编码.它不会抛出该异常.
我可以只围绕一个catch块,什么也不做的混账东西,但随后在任何情况下,怪物不会导致抛出异常,我不会发现它.我也不想创建一个throws UnsupportedEncodingException直到我的程序顶部的大型链.
我能在这做什么?为什么我不得不处理一些例外情况,而其他人(例如IllegalArgumentException,NullPointerException)我允许忽略?
来自C#,我只是没有得到在类/方法定义之后写的'抛出异常':
public void Test() throws Exception
Run Code Online (Sandbox Code Playgroud)
你要写这个吗?如果你不这样做怎么办?如果我调用具有此符号的方法,我是否必须捕获它?
我在SO上进行了这个伟大的讨论,标题为:针对已检查异常的情况,但是我无法遵循应该使用RuntimeException的地方以及它与正常异常及其子类的不同之处.谷歌搜索给了我一个复杂的答案,也就是说,它应该用于处理编程逻辑错误,并且应该在没有正常情况发生时抛出,例如在switch-case结构的默认块中.
你能否在这里详细解释一下RuntimeException.谢谢.
我目前正在审查同事的Java代码,我看到很多情况下,每个可能抛出异常的语句都被封装在自己的try/catch中.catch块都执行相同的操作(哪个操作与我的问题无关).
对我而言,这似乎是一种代码味道,我记得在阅读它是一种常见的反模式.但是我找不到任何关于此的参考.
因此,每个抛出的异常语句都会尝试使用try/catch,异常会被认为是反模式,支持这种情况的论据是什么?
构造示例:(与原始问题无关,所以请不要介意此示例中的其他问题,因为它只是为了说明我的意思而构建的.)
public int foo()
{
int x, y = 7;
try
{
x = bar(y);
}
catch(SomeException e)
{
return 0;
}
try
{
y = baz(x,y);
}
catch(SomeOtherException e)
{
return 0;
}
/* etc. */
return y;
}
Run Code Online (Sandbox Code Playgroud)
(假设在这里捕获两个异常是合适的,即我们知道它们是做什么的,并且适当的是在两种情况下都返回0.)