Java-Exceptions

  • each time compiler catch a failure, it will through an exception and terminate execution
    • if didn`t catch, terminate and show error message
  • each exception is in different and all class can call exception
    • useful when programmer want to check if input satisfy precondition
      • use if for case you know what is error
        • if(){ throw new exception(“error message”) }
      • use try-catch  when you don not know what might happen and program fail
        • try{   }catch(exception){print”***”; terminate/redo}
        • add finally block at the end of try-catch block
          • do no matter exception catch or not
          • finally executed
        • always do something or at least print a message and terminate the program when you catch a exception(do nothignexception is called Squelch Exceptions)
      • add throw Exception after function header when you try to throw exception in that function
      • when exception is catched, the execution is paused and check if exception is called in method it throw
        • if so, that`s where pick up
        • else, keep track the exception until catch where happened
        • continue until hit main method, if still not find, print error message and terminated
      • so if code may trigger exception, put it inside try box and use catch to catch error
        • if detected, program immediately jump to catch section and do part inside catch
  • lecture6arrays
  • code won`t check runTime exception but check others
    • try to handle with if()  bacuse it caused by programmer
    • other exception caused by compiler it will catch

 

 

  • tip
    • throw early
      • throw a exception  rather than come up with imperfect fix
    • catch late
      • catch exception only if the situation can be fixed
      • otherwise, let other part throw exception rather than catch it and do nothing

留下评论