I have read multiple posts on StackOverFlow about checked vs unchecked exceptions. I'm honestly still not quite sure how to use them properly.
Joshua Bloch in "Effective Java" said that
Use checked expections for recoverable conditions and runtime exceptions for programming errors (Item 58 in 2nd edition)
Let see if I understand this correctly
Here is my understanding of a checked exception:
try{
String userInput = //read in user input
Long id = Long.parseLong(userInput);
}catch(NumberFormatException e){
id = 0; //recover the situation by set the id to 0
}
1. Is the above consider a checked exception?
2. Is RuntimeException an unchecked exception?
Here is my understanding of a unchecked exception
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);?
}
4. Now, couldnt the above code also be a checked exception? I can try to recover the situation like this? Can I? (Note: my 3rd question is inside the catch
above)
try{
String filePath = //read in from user input file path
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){
//Kindly prompt the user an error message
//Somehow ask the user to re-enter the file path.
}
5. Why do people do this?
public void someMethod throws Exception{
}
Why do they let the exception bubble up? Isn't handling the error sooner better? Why bubble up?
EDIT: Should I bubble up the exact exception or mask it using Exception?
Below are my readings
In Java, when should I create a checked exception, and when should it be a runtime exception?
DataSeries
class that holds data which always must remain in time-based order. There is a method to add a newDataPoint
to the end of aDataSeries
. If all of my code is working correctly throughout the project, aDataPoint
should never be added to the end which has a prior date to the one already on the end. Every module in the whole project is built with this truism. However, I check this condition and throw an unchecked exception if it happens. Why? If it happens, I want to know who is doing this and fix it. – Erick Robertson May 24 '11 at 19:53