我已经在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
我维护一个Web应用程序,其中包含一个带有JSF标记的页面<f:event.我在服务类中重写了一个方法,以便抛出一个业务异常.但是,当抛出业务异常时,它不会被托管bean捕获,并且页面上会显示异常.似乎我的代码try/catch不起作用.
在XHTML中:
<f:event listener="#{resourceBean.init(enrollment)}" type="preRenderView" />
Run Code Online (Sandbox Code Playgroud)
Managed Bean中的监听器方法:
private boolean canCreateResource;
public void init(Enrollment enrollment) {
(...)
try {
canCreateResource = resourceService.canCreateResource(enrollment);
} catch (BusinessException e) {
canCreateResource = false;
}
}
Run Code Online (Sandbox Code Playgroud)
服务类中的方法:
public boolean canCreateResource(Enrollment enrollment) {
if (...) {
if (mandateService.isCoordinator(user, course)) {
return true;
} else {
throw new BusinessException("Undefined business rule.");
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
从我在其他网站上看到的内容,我想我必须实现一些JSF的处理程序类.但是哪个以及如何?
EDITED
OBS 1:BusinessException该类扩展了RuntimeException类.
OBS 2:canCreateResource创建属性以控制按钮的渲染.