Chapter 6: Exceptions and Assertions Flashcards
Checked Exceptions
java. text.ParseException (Converting String to number)
java. io.IOException
java. io.FileNotFoundException
java. io.NotSerializableException
java. sql.SQLException
Runtime Exceptions
ArrayStoreException (Storing wrong data in an array)
DateTimeException (Invalid format string for a data)
MissingResourceException (Access a key or resource bundle which doesn’t exist)
IllegalStateException/UnsupportedOperationException: Running an invalid operation on Collections and Concurrency.
Keys points from OCA
Java looks at catch blocks in order, so you can't have a subclass after a superclass since this is unreachable code. Can't have a catch block for a checked Exception when tone can't be thrown (unreachable code) If a method can throw an exception, must declare it throws at least that.
Creating your own Exception
Checked - extend Exception
Runtime - extend Runtime Exception
Multi catch
try {} catch (Exception 1 | Exception 2 e) {} Can be listed in an order, but can only have one variable at the end. Multi catch is meant for unrelated Exceptions. E.g. if one type is a subclass of the other, it won't compile. Can't reassign the variable in a multi-catch clause. But you can with a single-catch clause.
Try-with-resources
Permitted to omit catch and finally clauses. E.g. try(Resource to be closed) {} e.g. try (BufferedReader r = Files.newBufferredReader(path1)) Resource is closed automatically by Java. The resource is only available in the try clause.
Auto Closeable
Class needs to extend AutoCloseable in order for Java to be able to close automatically in a try-with-resources block.
Implementation needs to override void close() {} throws Exception method. Note: implementation can throw any more specific exception that they choose.
If method throws Exception, the method of the caller needs to throw it too.
Suppressed Exceptions
When multiple exceptions are thrown, all but the first one are called suppressed exceptions.
What if we have 2 resources we’re trying to close and they both throw Exceptions? Java tried to close them in.reverse order, then the first one throws the primary Exception while the other is suppressed.
Note: the Java catch block will only ever try to match on the primary exception.
Assertions
assert boolean_expression assert expression : error_message; You're allows () around the boolean expression. You can enabled/disable assertions by running java -ea program. You can run with just a single class, or subclasses having them enabled e.g. java -ea: path.to.class Program When running from command line if you don't specific -ea then assertions are not enabled. java -da -ea: path.to.class disabled them globally but enables them for a single class