processExceptions()应该调用BEAN.methodThrowExceptions方法并处理异常:1.1。如果发生异常FileSystemException,则通过调用BEAN.log方法将其记录下来并向前抛出。
1.2。如果出现异常CharConversionException或任何其他IOException,只需通过调用BEAN.log方法对其进行记录。
processExceptions()方法签名。main()中处理剩余的异常并记录它。使用try..catch我尝试了不同的解决方案。它起作用了,但不像它应该的那样。throws在方法中的正确位置是什么?或者我根本不应该用它们?如果我不放置它们,我就不能使用throw。请帮忙,我非常感谢您的时间。
public class Solution {
public static StatelessBean BEAN = new StatelessBean();
public static void main(String[] args) {
try{
processExceptions();
}
catch (CharConversionException e){
BEAN.log(e);
}
}
public static void processExceptions()throws CharConversionException {
try{
BEAN.methodThrowExceptions();
}
catch (CharConversionException e){
BEAN.log(e);
throw e;
}
catch (FileSystemException e){
BEAN.log(e);
}
catch (IOException e){
BEAN.log(e);
}
}
public static class StatelessBean {
public void log(Exception exception) {
System.out.println(exception.getMessage() + ", " + exception.getClass().getSimpleName());
}
public void methodThrowExceptions() throws CharConversionException, FileSystemException, IOException {
int i = (int) (Math.random() * 3);
if (i == 0)
throw new CharConversionException();
if (i == 1)
throw new FileSystemException("");
if (i == 2)
throw new IOException();
}
}
}发布于 2014-02-28 11:34:48
如果一个方法能够抛出一个非RuntimeException的异常(直接抛出或调用一个可以抛出异常的方法),它应该处理异常或声明它抛出异常,这样任何其他调用该方法的方法都会知道它可能遇到异常,并且可以处理它或者声明它抛出(等等)。
由于您正在处理检查过的异常,因此没有避免声明抛出的干净方法,但是有一个(混乱的)解决方法。您可以将异常包装在RuntimeException中并抛出它,当您想要处理它时,可以从re.getCause()获得实际的异常;
public class Solution {
public static StatelessBean BEAN = new StatelessBean();
public static void main(String[] args) {
try{
processExceptions();
}
catch (RuntimeException re){
if (!(re.getCause() instanceof CharConversationException)) {
//handle the case in which the exception was not CCE and not FSE not IOException
}
}
}
public static void processExceptions() {
try{
BEAN.methodThrowExceptions();
} catch (CharConversionException cce){
BEAN.log(e);
throw new RuntimeException(cce);
} catch (FileSystemException fse){
BEAN.log(e);
} catch (IOException e){
BEAN.log(e);
}
}
public static class StatelessBean {
public void log(Exception exception) {
System.out.println(exception.getMessage() + ", " + exception.getClass().getSimpleName());
}
public void methodThrowExceptions() throws CharConversionException, FileSystemException, IOException {
int i = (int) (Math.random() * 3);
if (i == 0)
throw new CharConversionException();
if (i == 1)
throw new FileSystemException("");
if (i == 2)
throw new IOException();
}
}
}我不知道我是否正确地理解了你的问题,这就是你想要的:)
发布于 2017-04-19 13:55:16
我认为命令:
在main()方法中处理剩余的异常
这意味着您不仅应该捕获CharConversionException,还应该通过以下方式捕获所有其他异常:
catch (Exception e)另外,你应该在help.javarush.net上问我想:>
https://stackoverflow.com/questions/22092992
复制相似问题