110 likes | 244 Views
Exceptions. common exceptions throwing standard unchecked exceptions. A Story….
E N D
Exceptions common exceptions throwing standard unchecked exceptions Fran Trees: AP CS Workshop
A Story… You plan a trip to HersheyPark, with the primary purpose of riding the roller coasters. Just after you pay for admission and pull out the map to look for the first roller coaster, the sky turns dark, and you see lightning and hear thunder. An announcement on the loud-speaker says that the park is closing. Fran Trees: AP CS Workshop
A Story…CCJ AP CS Study Guide (Chapter 12) An exceptional situation causes abrupt termination of the normal processing (the park visit). Note that throwing an exception doesn't tell you how to recover from the exceptional situation. An example of recovery would be if the management issued rain-checks. In Java, a catch clause is responsible for recovering from an exceptional condition. Fran Trees: AP CS Workshop
An exception is: • an "exceptional event" • an event that occurs during program execution that disrupts normal flow • not necessarily "an error." Fran Trees: AP CS Workshop
Some exceptions/errors • division by zero • accessing out-of-bounds array element • attempting to open non-existent file • attempting to read beyond eof marker • invalid class casting • specifying negative array sizes Fran Trees: AP CS Workshop
Java Exception Hierarchy Fran Trees: AP CS Workshop
Java Exception Hierarchy Checked exceptions are compiler-enforced exceptions. This means that when you call a method that throws a checked exception, you must tell the compiler what you are going to do about the exception if it is thrown. Checked exceptions are due to external circumstances that the programmer cannot prevent. (NOT part of AP Subset) Fran Trees: AP CS Workshop
AP CS A Subset • common exceptions • throwing standard UNCHECKED exceptions • unchecked exceptions can be ignored by the programmer; no need to use try/catch to handle the exception • not tested: • try/catch Fran Trees: AP CS Workshop
Java Exception Hierarchy Fran Trees: AP CS Workshop
AP CS A Subset • Students are expected to understand • NullPointerException • ArrayIndexOutOfBoundsException • ArithmeticException • ClassCastException • Students are expected to be able to throw • IllegalStateException • signals that a method has been invoked at an illegal or inappropriate time. • NoSuchElementException • if no more elements exist (useful with iterators) Fran Trees: AP CS Workshop
A look ahead… public void add(Locatable obj){ Location loc = obj.location(); if (!isEmpty(loc)){ throw new IllegalArgumentException("Location “ + loc + " is not a valid empty location"); } //Add object to the environment. theGrid[loc.row()][loc.col()]= obj; objectCount++; } Fran Trees: AP CS Workshop