I have noticed a large amount of posts that are doing something along the lines of
The reason that methods throw exceptions, is that the creators of that method believe that the program can still be saved. EG
/** * If the program is in debug mode */ public final boolean DEBUG = true; /** * Some Instance String */ private String someString; /** * Get the first line from a file and save it to a variable */ public void getFirstLine(File f) { try { BufferedReader in = new BufferedReader(new FileReader(f)); someString = in.readLine(); in.close(); }catch(IOException e) { if(DEBUG) { e.printStackTrace(): } System.err.println("An error occured reading the file, setting default properties"); someString = "Yellow Unicorn"; } }
Here is a quote from the Exception API
Originally Posted by Exception API
try { someExceptionThrowingMethod(); }catch(Exception e) { e.printStackTrace(); return; }
try { someExceptionThrowingMethod(); }catch(Exception e) {}
When you use an empty catch statement, you are inviting NullPointerException's and other bizarre errors much further along your program, because you caught the exception, but didn't attempt to save the program. Almost all of the time, Exceptions can be handled. Get a FileNotFoundException? Create a default file. Try-Catch statements are not just to make your program messier, they are there to let you handle less-then-optimal situations. If they were expecting everyone to throw their exception because it's program crashing, they would of used a error.
Originally Posted by Error API
Example of an error, (IOError)
Originally Posted by IOError API
The hybrid of errors and exceptions are unchecked exceptions. These include NumberFormatException's, NullPointerException, ArithmeticException, etc. These you can, and are very likely going to catch at some point or the other. NumberFormatException is caught is popular in programs deciding if a String is a number. EG:
/** * @returns 1 if the String is an Integer, 2 if the String is a Long, 3 if the String is a Double, 4 if the String is a * BigInteger, and 5 if the Stirng is not a Number. */ public int getType(String theStr) { try { Integer.valueOf(theStr); return 1; }catch(NumberFormatException) //Extends IllegalArgumentException, so does not have to be caught. (IllegalArgumentException extends RuntimeException) { //Do nothing, not a Integer. /* * While normally I say that you should never have an empty catch statement, * in this scenario it can be expected that an exception will occur. This * is very often the case with unchecked exceptions. */ } try { Long.valueOf(theStr); return 2; }catch(NumberFormatException) { //Do nothing, not a Long } try { Double.valueOf(theStr); return 3; }catch(NumberFormatException) { //Do nothing, not a Double. } //Check if it is a HUGE number. (BigInteger) try { new BigInteger(theStr); return 4; }catch(NumberFormatException) { //Do nothing, not a BigInteger } //Not a number return 5; }