Download Classes and Methods

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Title Slid
CSC 444
Java Programming
Exceptions
By
Ralph B. Bisland, Jr.
Exceptions
• A robust program deals gracefully with
unexpected situations/conditions.
• Exceptions are unusual conditions that
could arise when code is executing.
• The exception could make the
continuation of the execution of the
program impossible or undesirable.
• Examples of exceptions include:
– Divide by zero
– Arithmetic overflow
– index out of bounds
2
Exceptions (ctd)
• In Java terminology, exceptions are
“thrown”.
• Exceptions may be system defined or user
defined.
• Exceptions may be thrown by the system
of by the programmer.
• Exception are “caught” with exception
handlers - which is code that executes if
the exception occurs.
• If no handler is written for the exception,
the program terminates execution.
3
Exceptions (ctd)
• There are 20+ subclasses of Exceptions
which are defined in the package
java.lang.Throwable
4
Exception Hierarchy
Object
Throwable
Error
Exception
RunTimeException
5
Exception Explanations
• Throwable: Superclass for all error
handling. This class should not be used
directly to describe a particular exception.
• Error: Indicates a severe problem from
which recovery is difficult, if not
impossible. Example: Running out of
memory. It is probably best to report the
error, then terminate execution of the
program.
6
Exception Explanations (ctd)
• Exception: Super class for
RunTimeExceptions.
• RunTimeException: Indicates a design or
implementation problem. Example:
IndexOutOfBoundsException. An attempt
should probably be made to fix this type
exception and continue execution of the
program.
7
Partial Exception Hierarchy
Object
Throwable
Exception
RuntimeException
ArithmeticException
ArrayStoreException
ClassCastException
IllegalArgumentException
NumberFormatException
IllegalMonitorStateException
IndexOutOfBoundsException
ArrayIndexOutOfBoundsException
StringIndexOurOfboundsException
NegativeArraysizeException
NullPointer Exception
SecurityException
8
Checked Exceptions
• An exception to can be analyzed by the
compiler.
– A checked exception must either be handled
in the method or declared in the method
signature via the throws clause.
– Example: IOException
– Designed to reduce the number of errors that
could occur in program execution.
9
Unchecked Exceptions
• A subclass of RuntimeExceptions.
These exceptions are not checked by
the compiler because they would be
difficult to check at compile time.
– Examples: ArithmeticException and
NullPointerException.
10
Try-Catch
• To handle exceptions any block of code in
which the exception could possible occur
must be preceded by the “try” statement.
• If present the catch block(s) must lie
directly below its try block.
• There may be multiple catch blocks, each
catching a separate exception.
• Once the code in the exception handler is
executed, control leaves the block.
11
Example
try {
some java code that could cause an
exception to be thrown
}
catch (exception-type identifier)
{
code to handle the exception
}
12
A More Specific Example
int x =;
try
{
x = SimpleInput.readInt();
}
Catch (NumberFormatException nfe)
{
System.out.println
(“You entered an illegal integer value”);
}
Note: When this error occurs, the file pointer
Does not move and the value currently stored
In the variable ‘x” does not change.
13
Another Example
class TestException
{public static void main (String[] args)
{String greetings [] =
{“Hello there, I‘m Yogi Bear”,
“Hi Boo-Boo”,
“Welcome to Jellystone Park”};
for (int i = 0; i<= 3; i++)
System.out.println (greetings[i]);
}
}
14
Output
orca% javac TestExc.java
orca% java TestExc
Hello there, I'm Yogi Bear
Hi Boo-Boo
Welcome to Jellystone Park
java.lang.ArrayIndexOutOfBoundsException
at TestExc.main(TestExc.java:8)
orca%
15
Displaying Exceptions
• A method called toString can be used to
convert the exception to text for display.
• Example:
catch (Exception e)
{system.out.println
(e.toString);}
16
With Exceptions
class TestException
{public static void main (String[] args)
{String greetings [] =
{“Hello there, I‘m Yogi Bear”,
“Hi Boo-Boo”,
“Welcome to Jellystone Park”};
for (int i = 0; i<= 3; i++)
try{System.out.println (greetings[i]);}
catch (Exception e)
{System.out.println(e.toString());}
}
}
17
Output
orca% javac TestExc1.java
orca% java TestExc1
Hello there, I'm Yogi Bear
Hi Boo-Boo
Welcome to Jellystone Park
java.lang.ArrayIndexOutOfBoundsException
orca%
18
The exit() Method
• The exit() method is used to terminate
execution of a Java program.
• An integer value must be “passed” to the
exit method. This value is displayed as
output so if there is more than one “exit”
point, the programmer will know which
exit caused termination of the program.
• Example:
exit(0);
19
Unhandled Exceptions
• If the exception is not handled in the
current block, control is transferred to
the next outermost block when it may be
handled.
• This process is called propogation of
exceptions.
• If the exception eventually gets to the
outermost block and is still not handled,
execution of the program terminates,
20
Example
public static int processInput (……)
{
int x;
. . .
x = SimpleInput.readInt();
// Normal processing continues
. . .
}
Because there is no exception handler in the
Block control is passed to the next
outermost block. Problem: No value returned
by the method.
21
Editing Input
…
boolean inputReadOK = false;
While (!inputReadOK)
try{
x = processInput (…);
}
catch (NumberFormatException
{System.out.println (e);
SimpleInput.readLine();//
System.out.println(“Input
}
inputReadOK = true;
// normal processing continues
e)
Move the file ptr
error try again”);
here
22
A Complete Example
import java.lang.*;
import SimpleIO.*;
class TestException
{public static void main (String [] args)
{int aNumber;
boolean success = false;
String inputString = “”;
System.out.print (“Enter an integer: “);
while (!success)
{
try { aNumber = SimpleInput.readInt();
success = true;}
catch (NumberFormatException e)
{inputString = SimpleInput.readString();
System.out.println (“The string: “ +
inputString + “is not an integer” +
“-- try again”);}
}
System.out.println (“You entered the integer value: “ +
aNumber);
}
23
Catching Multiple Exceptions
• Multiple exceptions can be caught by
including multiple catch blocks after the
try block.
• Example:
try{
}
catch (exception1 e1)
{code for this exception}
catch (exception2 e2)
{code for this exception}
24
The Finally Clause
• The finally clause associated with a try
block ensures that a set of code will be
executed whether the exception is thrown
or not.
• The code in the finally block is usually
referred to as ‘clean up” code.
• It is often used to do things like close files,
write out final messages, etc.
25
Example
Class FinallyTest
{public static int aMethod (. . .)
{. . .
try { . . . }
catch (IOException e) { . . .}
. . .
try { . . . }
catch (EOFException e) { . . .}
finally { . . . }
}
public static void main (String[] args
{ . . . }
}
26
Another Example
class TestException
{public static void main (String[] args)
{String greetings [] =
{“Hello there, I‘m Yogi Bear”,
“Hi Boo-Boo”,
“Welcome to Jellystone Park”};
for (int i = 0; i<= 3; i++)
try{System.out.println (greetings[i]);}
catch (Exception e)
{System.out.println(e.toString());}
finally {System.out.print
(“Always displayed”);}
}
}
27
Output
orca% javac TestExc2.java
orca% java TestExc2
Hello there, I'm Yogi Bear
Always displayed
Hi Boo-Boo
Always displayed
Welcome to Jellystone Park
Always displayed
java.lang.ArrayIndexOutOfBoundsException
Always displayed
orca%
28