Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines.

Similar presentations


Presentation on theme: "Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines."— Presentation transcript:

1 Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines a problem that can usually be fixed.

2 Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled by another part of the program A program can be separated into a normal execution flow and an exception execution flow An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught

3 Exception Handling Java has a predefined set of exceptions and errors that can occur during execution A program can deal with an exception in one of three ways: ignore it handle it where it occurs handle it an another place in the program

4 Exception Handling If an exception is ignored by the program, the program will terminate abnormally and produce an appropriate message The message includes a call stack trace that indicates the line on which the exception occurred The call stack trace also shows the method call trail that lead to the attempted execution of the offending line Read after the slide: Handling exceptions is not required on the AP test. However, you should be familiar with common exceptions and throwing exceptions.

5 throw new NoSuchElementException();
The throw Statement Exceptions are thrown using the throw statement Usually a throw statement is nested inside an if statement that evaluates the condition to see if the exception should be thrown The statement at the bottom of the slide throws a NoSuchElementException: These exceptions are known as user-defined exceptions. In order to throw user defined exceptions, the throw keyword is being used. The purpose of the exception is to handle code that doesn’t behave in the way that is expected. throw new NoSuchElementException();

6 Here is an example of a thrown exception with a try / catch block to handle the exception. In this example, we are catching invalid input from the user. The user will not see the exception string literal text “Age can’t be less than zero” but the string literal will assist the programmer in determining the reason the code did not work as intended.


Download ppt "Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines."

Similar presentations


Ads by Google