Exceptions

  • Eceptions are basically a way of handling errors that come up
  • Not necessary but good
  • Sometimes easier to check for return value

Main Benefits

  • Allows you to keep error handling code out of the main flow of program
  • Too many if statements if you don't use eceptions

Eception Terminology

  • When a function comes across an exceptional situation, it should throw an exception
    • An eception that was thrown should then be handled in a specific way, so that the program can recover or exit gracefully.
  • When calling a function that throws an ecveption, the function may complete successfully, or it may fail
  • Therefore, when you call the function, you are going to try it and see what happens
  • Within a try block, an eception mightget thrown -In order to correctly handle that exception, we must make an attempt to catch the eception that was thrown A catch blok should come after a try block to handle the exception Finall, whether or not an eception was thrown, there may be some stuff you want to do Statements in a finally block will always be executed, regardless of whther or not an exception was thrown or not

Exception Propagation

  • A thrown exception will continue to proapgate up the call stack until it is caught
  • can be caught by a catch that catches the excet type of thrown exception
  • Can be caught by a catch that ctatches any parent class of the exception type thrown
  • As exception proagates upward
    • Checks fcor appropriate catch block

Catch All

  • Since all exceptions are derived from excetpio, you can catch all types of eceptions with:
  • catch (Exception excep); // much like catch-all
  • The catch-all is good when treating all exceptions as catastrophic
  • Place a catch-all in main, report an eception was thtrown and die gracefully
  • Generally though, there is a better way to handle eceptions so the catch-all is not usually recommended
  • Can use the instanceof operator to dermine what type of exception it was

results matching ""

    No results matching ""