相关疑难解决方法(0)

Java:已检查vs未经检查的异常说明

我已经在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

678
推荐指数
11
解决办法
31万
查看次数

如何在java中对字符串格式的日期进行排序?

我有一个arraylist像字符串值

ArrayList<String> datestring=new ArrayList<String>();
datestring.add("01/21/2013 @03:13 PM");
datestring.add("01/21/2013 @04:37 PM");
datestring.add("01/21/2013 @10:41 AM");
datestring.add("01/21/2013 @10:48 AM");
datestring.add("01/22/2013 @06:16 AM");
datestring.add("01/22/2013 @06:19 AM");
datestring.add("01/21/2013 @05:19 PM");
datestring.add("01/21/2013 @05:19 PM");
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我整理上面的清单吗?以便根据AM和PM格式对值进行排序.
排序后的预期输出应该是

for (String s : datestring)
{
    System.out.println(s);
}
Run Code Online (Sandbox Code Playgroud)

.

01/21/2013 @10:41 AM;
01/21/2013 @10:48 AM;
01/21/2013 @03:13 PM;
01/21/2013 @04:37 PM;
01/21/2013 @05:16 PM;
01/21/2013 @05:19 PM;
01/22/2013 @06:16 AM;
01/22/2013 @06:19 AM;
Run Code Online (Sandbox Code Playgroud)

java sorting datetime

28
推荐指数
4
解决办法
6万
查看次数

Java:为什么我不能在Comparator中抛出异常?

直接的答案是因为Comparator.compares接口被指定为不会抛出异常.但那是为什么呢?

或者说它不同:我Comparator必须依赖于可以抛出异常的函数.从理论上讲,这不应该发生.但如果它发生了,我希望它突破我使用它Comparator(in Collections.sort)的整个功能.即我希望它只是表现为发生了未处理的异常.

看起来这是不可能以一种明显的自然方式(因为如果接口说它不能抛出异常,它就不能).

我该如何解决这个问题?有一个丑陋的尝试/捕获并打印出异常并希望我认识到它?这似乎是一种非常丑陋的方式.

java exception-handling exception

6
推荐指数
2
解决办法
6391
查看次数