180 likes | 298 Vues
Exceptions. Please sit with your Tivoo Group. Today. You will build your own exception handling code You will know about some of the finer details of Java exceptions – general vs. specific exception types, finally clauses, RuntimeExceptions. int myValue = 0 try { myValue = 1;
E N D
Exceptions Please sit with your Tivoo Group
Today • You will build your own exception handling code • You will know about some of the finer details of Java exceptions – general vs. specific exception types, finally clauses, RuntimeExceptions
intmyValue = 0 try { myValue= 1; functionThatThrowsException(myValue) } catch (SpecificKindOfException e) { myValue= 3; } return myValue; • What does this function return, if functionThatThrowsException throws an exception? • 0 • 1 • If it throws SpecificKindOfException 3, otherwise 1 • If it throws SpecificKindOfException 3, otherwise 0 • If it throws SpecificKindOfException 3, otherwise it does not return
Basic Operation of Exceptions try { throw new ExceptionClass(“Some data”) } catch (OtherExceptionClass e) { //if OtherExceptionClass is the same as //ExceptionClass (or one if it’s superclasses) //we go here. Otherwise the exception continues // to the next try…perhaps outside of this function dealWithException(e.getData()); } An uncaught exception can easily end your program.
The Use of Exceptions Improves Your Code by Consolidating Error Handling int result1 = getData(); if(result1 != -1) { result2 = processData(result1); if(result2 != -1) { displayData(result2); return; } else { System.err.println(“Error processing data”); return; } else { System.err.println(“Error getting data”); }
Do not do this try { callFunction(); } catch (CatastrophicException e) { e.printStackTrace(); //just continuing on, maybe hiding this //error with later code, corrupting data //files } return;
Do not do this try { callFunction1(); } catch (Exception e) { e.printStackTrace(); } try { callFunction2(); } catch (Exception e) { e.printStackTrace(); }
The Use of Exceptions Improves Your Code by Consolidating Error Handling try { int result1 = getData(); result2 = processData(result1); displayData(result3); } catch (ProcessingException e) { //let the functions themselves //decide what to display in their //error System.err.println(e); }
The Use of Exceptions Improves Your Code By Making it Easy to Move Up the Call Hierarchy • In main, we request the user enter a file name. We take the name give and call process file. • In process file, we open the file and call doXMLParse • In doXMLParse we break the file into events. For each even we call parseEvent • In parseEvent we get the date string out of the event XML. Then we pass it to parseDate • In parseDate, we discover that that date string is malformed. ERROR!
The Use of Exceptions Improves Your Code by Allowing You to Report Relevant Data in Your Exception • If there is a parsing error, I want to know • What line of the data file the error occurred on • What the problematic text was • If I was “expecting” something – what was I expecting • If there is an SQL error writing to the database, I want to know • The SQL I was trying to execute • If there was an network error • The URL I was trying to read from • DO NOT hesitate to write your own exception classes!
Fail or Retry? • Some things are unreliable: a network connection – maybe it makes sense try again in a half second (but don’t get caught in an infinite loop) • Sometimes you can ignore a problem in a small part and still get 95% of what you need done • Often a retry is possible but the point of failure is not the place for a retry – throw and let the proper place catch • DO NOT let your code just return bad data and move the problem to someplace that’s harder to debug. Fail. • DO NOT do a retry without logging the problem • DO NOT accept that your code will frequently print meaningless error messages or other garbage (TERRIBLE STYLE)
Activity • Modify your parsing classes to use exceptions appropriately • Make your own exception classes – include every imaginable bit of useful error data (hint…you might have to add some tracking to allow detailed reporting) • For recoverable errors (e.g. problems with 1 entry out of many) log and recover
Today • You will build your own exception handling code • You will know about some of the finer details of Java exceptions – general vs. specific exception types, finally clauses, RuntimeExceptions
Don’t Make Your Catch Clauses General try { parse1(); parse2() parse3() } catch (Exception e) { //this code is a lie System.err.println(“Error parsing”); }
If this is ordinary… public void parseEvent() throws ParseException // callers are required to catch this, or throw // themselves
For More Unusual Circumstances if(db.isNotConnected()) { //This would be super bizarre throw new RuntimeException(“DB is not connected in function closeDB. What is up?”); }
Finally try { file.open(); //seriously this must be closed doABunchMoreStuff(file); } finally { // runs regardless of any exceptions that might // be thrown file.close(); } Try with Resources is a new feature in Java 7 that does a similar thing
Mikes Hints for Exceptions • Use exceptions to put error handling in the place where it belongs. Often, that means putting it very close to the user. • Always document everything you can (easily) in an exception • Prefer throw to returning a bogus value, especially one like null that can cause problems elsewhere • Know about runtime exceptions when you need quick & dirty “the world has exploded” exceptions • Don’t be shy about throwing or defining your own exception types