Docsity

More on Exceptions - Introduduction to Jave Programming - Lecture Slides, Slides of Java Programming

Partial preview of the text

Download More on Exceptions - Introduduction to Jave Programming - Lecture Slides and more Slides Java Programming in PDF only on Docsity!

More on Exceptions

Highlights

  • throws
  • finally

throws

So far we have used exceptions to handle runtime errors using try and catch blocks Exceptions should really be used to pass the issues to other parts of code This is because other parts of code might have more information or need to act accordingly

throws

throws

If an exception is thrown, the method will terminate You can chain throws in this manner through multiple methods If all the methods (including main()) chain the throw, you will crash with angry red text (See: ChainThrow.java)

finally

In addition to try and catch blocks, you can also put a finally block after the catch block

Exceptions are classes

Every file you have made has been a class It should come as no surprise that Exceptions are simply a type of class as well (they simply store some information) Similar to classes, you might need to import an exception in order to be able to use it (See: ImportException.java)

Exceptions in inheritance

When you override methods that you inherited, you can catch on less exceptions (more restrictive) Remember child's overridden method must be able to “fit into” the parent's method This means you...

  1. Remove exceptions
  2. Replace exceptions by a child (descendant) (See: InheritException and InheritExceptionParent.java)Docsity.com

Checked vs. Unchecked

Checked exceptions need to either..

  1. Have a try and catch block (or the code will not compile)
  2. Throw the exception Unchecked exceptions...
  3. Do not need to be thrown (but still can be caught)
  4. Will compile without being caught (See: UncheckedExceptions.java) Docsity.com

Checked vs. Unchecked

= Checked exceptions = Unchecked

Nested try-catch

It is possible to nest try-catch, but it is generally frowned upon You should either make a method for the inside try-catch, or simply catch at the outside (remove inside try) In addition to giving headaches, the inner try exception can fall through to the outer catch if the inner catch did not actually catchDocsity.com