Title: TCU CoSc 10403 Programming with Java
1TCU CoSc 10403 Programming with Java
2What is an Exception
- Imagine the following code that might appear in
some Applet - int age Integer.parseInt(ageTF.getText().trim(
)) - Obviously, we are expecting a number will appear
in the TextField and that it constitutes a legal
integer age. - Consider, however, the following possibilities
- What if the user types a instead of a 4 by
mistake? - What if the user enters a decimal point number
rather than an integer? - What if the user holds down the 3 key too long
and an extremely long number is accidentally
entered? - We dont expect circumstances such as these --
but they do happen! - Software must be designed to expect the
unexpected!!!
3What is an Exception
- Some things that can go wrong during the
execution of a program (such as on the earlier
slide) cant be detected at compile-time
because the user has not yet made the mistake by
entering the wrong data!! - Another example your program may attempt to
divide one number by zero (ex. examSum/numberOfStu
dents) - Or your program may require that an integer value
be entered into a TextField, and the user of the
program enters a float value or some other
illegal character. - From the compilers point of view, there is
nothing wrong with these statements, and problems
will arise only when the program is actually
executing. - At that point an internal alarm goes off, and
Java attempts to throw an exception signifying
that something untoward has occurred.
4Example
import java.awt. import java.applet. public
class TrivialApplet extends Applet
//------------------------------- //
Deliberately divides by zero // to produce an
exception. //-------------------------------
public void init() int numerator
10 int denominator 0
System.out.println ("This text will be
printed.") System.out.println (numerator /
denominator) System.out.println ("This
text will not be printed.") // because
exception // occurs prior to //
execution of this // statement
Note also There is no code to handle the
exception, if it occurs!
5What is an Exception
- The system then immediately halts its normal mode
of execution and goes off looking for help. - With luck, the system will find some code in your
program that will catch the exception and deal
with it. - Once caught, the alarm is silenced and the system
picks up execution at a location after the block
that contained the offending statement. - Jargon
- Java has its own terminology for exceptions.
- Exceptions are indicted by being thrown, and are
detected elsewhere by being caught.
6Terminology of 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 an unrecoverable
situation and should not be caught
7Some Possible Exceptions
ArithmeticException - something, such as
division by zero, has gone wrong in an arithmetic
expression NumberFormatException - indicates
that an illegal number format is being
used. StringIndexOutOfBoundsException - an
attempt has been made to use an inappropriate
String index. NullPointerException - a class
method is being called by an object instance that
is currently null. EOFException - an end-of-file
mark has been seen. IllegalArgumentException - a
method has been called with an invalid
argument. IndexOutOfBoundsException - an index
into an array is out of bounds.
8Exceptions
- As indicated on the earlier slide, 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 in another place in the program
- The manner in which an exception is processed is
an important design consideration
9Exceptions
- 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. Remember, an exception is an
object. - The getMessage method returns a string
explaining why the exception was thrown - The printStackTrace method prints the call stack
trace
10The try Statement
- To process an exception when it occurs, the line
that throws the exception is executed within a
try block - A try block is followed by one or more catch
clauses, which contain code to process an
exception - Each catch clause has an associated exception
type and is called an exception handler - When an exception occurs, processing continues at
the first catch clause that matches the
exception type
11Explanation of try block
- Java is instructed to try to execute a block of
statements. - If the statements in the block execute without
producing an exception, the catch block is
ignored, and execution continues beneath the
catch block. - However, if an exception is produced, we can
specify that the catch block is to execute by
stating the class of exception that we wish to
catch. - Basic form of try-catch block -
- try
-
- . . . //a series of statements to be
executed -
- catch (someException e)
-
- . . . // code to handle the exception
-
12Exceptions
import java.awt. import java.applet. public
class TrivialApplet extends Applet
//------------------------------- //
Deliberately divides by // zero to produce an
exception. //-------------------------------
public void init() int numerator
10 int denominator 0
System.out.println ("This text will be
printed.") try
System.out.println (numerator / denominator)
catch (ArithmeticException e)
System.out.println ("This text will
now be printed.")
13Another Example
import java.awt. import java.applet. import
java.awt.event. public class ExceptionDemo1
extends Applet implements ActionListener TextFi
eld stringField new TextField(20), resultField
new TextField(20) Label resultLabel new
Label ("Answer"), stringLabel new Label("Type
an integer") float number public void
init() resultField.setEditable(false) add
(stringLabel) add(stringField) stringField.a
ddActionListener(this) add(resultLabel)
add(resultField) public void
actionPerformed(ActionEvent event)
try number Float.parseFloat(stringFie
ld.getText().trim()) resultField.setText("Doubl
ed value " (2 number)) catch
(NumberFormatException e)
resultField.setText("Error in number -
retype")
14Exceptions
- As mentioned earlier, when a try block produces
an exception, its execution is terminated - it is
abandoned. - A consequence of this is that any variables
declared within the try block become inaccessible
and cannot be used in the catch block, even if
the catch block is in the same method. - This can be a problem if we want to use those
variables to produce a specific error message
detailing what caused the problem. - For example, you might want to display a wrongly
formatted string if it was not able to be
converted to an integer. - A simple solution - any variable that is required
inside the catch block must be declared outside
the try block.
15Examples
try String s tf.getText().trim()
int x Integer.parseInt(s)
catch (NumberFormatException e) .
. . // String s and int x not available here
String s tf.getText().trim() int x 0
//initialized to 0 because of Javas annoying
warning message try x
Integer.parseInt(s) catch
(NumberFormatException e) // string s is
available here since declared outside try
System.out.println(s input
e.toString()) System.out.println("Numb
er " x) Note 1500 entered into tf
produces Number 1500 1.5
produces 1.5 input java.lang.NumberFormat
Exception For input string "1.5 Number
0 //produced by System.out.println() that
appears after the catch xyz
produces xyz input java.lang.NumberFormatExc
eption For input string "xyz Number 0
//produced by System.out.println() that appears
after the catch
16The search for a Catcher
- What if the program doesnt catch a thrown
exception? - Actually, the rules for this depend on the class
of exception. - The basic principle is based on the fact that all
programs, for the most part, are made up of
methods. - Thus, at run-time, an initial method is invoked,
which itself invokes other methods, which in turn
invoke others, etc - Imagine that methodA() invokes methodB() which
invokes methodC(). - If an exception occurs in methodC(), the search
for an appropriate catch begins in methodC(). - If one is not found, the search moves to
methodB(), and then to methodA(), etc. - If the top-level method does not provide a catch,
an exception message is displayed and the program
terminates abnormally (for an applet, it will
continue to run and its results will be
unreliable).
17Still Another Example
import java.awt. import java.applet. import
java.awt.event. public class
AnotherExceptionExample extends Applet implements
ActionListener TextField numField new
TextField(15), denomField new TextField(15),
resultField new TextField(15) Label
resultLabel new Label ("Answer"), denomLabel
new Label("Enter the denominator"), numLabel
new Label("Enter the numerator") public void
init() add(numLabel)
add(numField) numField.addActionListener(th
is) add(denomLabel) add(denomField)
denomField.addActionListener(this)
add(resultLabel) add(resultField)
resultField.setEditable(false) public void
actionPerformed(ActionEvent event) try
int numerator Integer.parseInt(numField.get
Text().trim()) int denominator
Integer.parseInt(denomField.getText().trim()) r
esultField.setText("" numerator/denominator)
catch (NumberFormatException e1)
resultField.setText("Error in number - ")
catch (ArithmeticException e2)
resultField.setText("Divide by Zero")
//continue here afterwards
18Finally, finally
- The finally clause is used for activities that
should be performed whether or not an exception
was thrown and caught. - Syntax
- finally
-
- //cleanup code
-
- A try block can have at most one finally clause,
and it must appear immediately after the last
catch clause. - The block of a finally clause is guaranteed to be
executed, no matter how controls leaves its try
block. - If none of the catch clauses is executed, the
finally clause is executed after the try block. - If one of the catch clauses is executed, the
finally clause is executed after completion of
the catch. - The finally clause is executed even if the try or
catch portions contain break or return
statements.