L14 Exception
-
Upload
tsion-kiffle -
Category
Documents
-
view
225 -
download
0
Transcript of L14 Exception
-
8/3/2019 L14 Exception
1/37
MIT AITI 2003
Lecture14
Exceptions
Javas Error handling mechanism
-
8/3/2019 L14 Exception
2/37
Objectives(we will see if we have achieved them at the end of the day)
How to use methods that cause exceptions
How to respond to exceptions in your Java
programs
How to create methods that ignore an
exception, leaving it for another class to
handle
How to create your own exceptions
-
8/3/2019 L14 Exception
3/37
SampleProgram (1)
-- Whats the output of the following program?
public class SampleProgram {
public static void main(String args[]) {
String[] greek = {"Alpha", "Beta", "Gamma"};
System.out.println(greek[3]);
}
}
-
8/3/2019 L14 Exception
4/37
SampleProgram (2)
--The output
java.lang.ArrayIndexOutOfBoundsException
at SampleProgram.main(SampleProgram.java:5)
Exception in thread "main"
-
8/3/2019 L14 Exception
5/37
SampleProgram (3)
--Notes Compiles successfully but encounters a problem when it
runs
The Java interpreter made note of the exception by
displaying the error message and stopped the program.
An object of type ArrayIndexOutOfBoundException is
created to alert the useryou have used an array element
that isnt within the arrays boundaries.
ArrayIndexOutOfBoundException is a subclass of
Exception
-
8/3/2019 L14 Exception
6/37
Some words about Exceptions
All exceptions are subclasses ofException.
Some exceptions are comparable to compiler
errors, e.g. ArrayIndexOutOfBoundsException Others must be dealt with every time a program
runsyou cant deal with or you want to handle
them within a Java class
Exception handling is done using these five
statements: try, catch, finally, throw and throws
-
8/3/2019 L14 Exception
7/37
SumNumbers (1)
public class SumNumbers {
public static void main(String[] arguments) {
float sum = 0;for (int i=0; i
-
8/3/2019 L14 Exception
8/37
SumNumbers (2)
java SumNumbers 8 6 7 5 3 0 9
Output:
Those numbers add up to 38.0
Java SumNumbers 1 3 5xOutput?
-
8/3/2019 L14 Exception
9/37
SumNumbers (3)
java.lang.NumberFormatException: 5x
at java.lang.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1176)
at java.lang.Float.parseFloat(Float.java:183)
at SumNumbers.main(SumNumbers.java:7)
Exception in thread "main"
-
8/3/2019 L14 Exception
10/37
Catching Exceptions in a try-
catch Block
-
8/3/2019 L14 Exception
11/37
NewSumNumbers(1)
public class NewSumNumbers {
public static void main(String[] arguments) {
float sum = 0;
for (int i=0; i
-
8/3/2019 L14 Exception
12/37
NewSumNumbers(2)
Java NewSumNumbers 1 3 5x
Output:
5x is not a number.
Those numbers add up to 4.0
-
8/3/2019 L14 Exception
13/37
-
8/3/2019 L14 Exception
14/37
Catching Several Different
Exceptions
-
8/3/2019 L14 Exception
15/37
public class DivideNumbers {
public static void main(String[] arguments) {
if (arguments.length == 2) {
int result =0;
try {result = Integer.parseInt(arguments[0])/Integer.parseInt(arguments[1]);
System.out.println(arguments[0] + " divided by " + arguments[1] + " equals " + result);
}
catch (NumberFormatException e) {
System.out.println("Both arguments must be numbers.");
}catch (ArithmeticException e) {
System.out.println("You cannot divide by zero");
}
}
}
}
-
8/3/2019 L14 Exception
16/37
Handling Something After an
Exception
-
8/3/2019 L14 Exception
17/37
try-catch-finally block
try{
//statement(s) that might cause the exception
}catch (Exception e) {
//what to do when the exception occurs
}
finally {//statements to execute no matter what
}
-
8/3/2019 L14 Exception
18/37
Throwing Exceptions
-
8/3/2019 L14 Exception
19/37
-
8/3/2019 L14 Exception
20/37
public class NewSumNumbers {
public static void main(String[] arguments) {
float sum = 0;
for (int i=0; i
-
8/3/2019 L14 Exception
21/37
public class NewSumNumbers {
public static void main(String[] arguments) throws NumberFormatException {
float sum = 0;
for (int i=0; i
-
8/3/2019 L14 Exception
22/37
Create your own exception class
-
8/3/2019 L14 Exception
23/37
Writing Your Own Exception Classes
Writing your own exception class is simple.
New exception classes allow you to handle a new type oferror separately.
Exception classes extendjava.lang.Exception.
public class DataFormatException
extends java.lang.Exception {
public DataFormatException(){ super(); }
public DataFormatException(String s)
{ super( s ); }
}
-
8/3/2019 L14 Exception
24/37
Exception Objects -Structure 2 Constructors
the default constructor with no argument
the constructor that takes a string (errormessage) argument
getMessage() method
return the error message string(the argument of the 2nd constructor)
-
8/3/2019 L14 Exception
25/37
Creating and Throwing
your own Exception instances Exceptions are objects. You must create a
new instance of an exception before you
can throw itif ( dArray.length == 0 )
throw new
IllegalArgumentException();
-
8/3/2019 L14 Exception
26/37
Declaring an Exception If a method can throw an exception, you can always declare the type
of the exception in the header after the keyword throws
public static double average( double [] dArray )
throws IllegalArgumentException The compiler requires you to declare the possible exception throw if
the exception class is not derived from RuntimeException orError. These are called checked exceptions (checked by thecompiler).
Exceptions derived from RuntimeException are calledunchecked exceptions and their declaration is optional.
-
8/3/2019 L14 Exception
27/37
27
Throwing an Exception
-- An Examplepublic static double average( double [] dArray )
throws IllegalArgumentException{
if ( dArray.length == 0 )throw new IllegalArgumentException();else
{
double sum = 0.0;
for ( int i = 0; i < dArray.length; i++ )sum += dArray[ i ];
return sum / dArray.length;}
}
-
8/3/2019 L14 Exception
28/37
Exceptions, Errors, and
RuntimeExceptions Throwable have two special subclasses: Error and Exception
Error: a catastrophic failure (your program will not be able torecover)
Exception: a non-catastrophic failure (your program shouldrecover or exit gracefully)
RuntimeException (unchecked Exception): a specialsubclass of Exception. Methods and constructors throwing
RuntimeExceptions do not have to declare this fact. All other exceptions (checked exception): methods orconstructors throwing checked exception should declare thisfact.
-
8/3/2019 L14 Exception
29/37
Checked vs. Unchecked Exceptions
In principle, checked exceptions are those which you, theprogrammer, are supposed to be able to fix at runtime, such as aFileNotFoundException. Very often these are generated insystem code by user, not programmer error.
Unchecked exceptions (RuntimeExceptions) are supposed to beable to occur anywhere (so hard to check for) and to be the result ofprogrammer error (so the best way of handling them is to fix theprogram).
Good examples of unchecked exceptions: NullPointerException,ArrayIndexOutOfBoundsException.
Bad example of unchecked exceptions, NumberFormatException,thrown e.g. by Float.parseFloat(String s).
-
8/3/2019 L14 Exception
30/37
Recap:
When things go wrong What happens when things go wrong?
How do I create alternative ways to handle
atypical circumstances? Do you know the followings?
How to use methods that cause exceptions
How to respond to exceptions in your Java programs
How to create methods that ignore an exception,
leaving it for another class to handle
How to create your own exceptions
-
8/3/2019 L14 Exception
31/37
Expecting the unexpectedtypes of Unexpected Circumstances
Catastrophic failures: can not be prevented, but
certain systems need to design in mechanisms to
minimize the damage that they cause Some failures: can be anticipated and avoided
through simple checks and guards.
Other failures: must be handled as they arise,often use Javas exception handling mechanism.
-
8/3/2019 L14 Exception
32/37
How would you classify these
situations? Someone tripped over the power cord of
the computer on which your program was
running. Divisor is 0 for a division operation.
The arguments dont match the signature of
the methods.
-
8/3/2019 L14 Exception
33/37
Whats wrong here?
public static int [] add(int [] n1, int [] n2) {
int [] n3 = new int[n1.length];
for (int k = 0; k
-
8/3/2019 L14 Exception
34/37
Lets write an exception to handle the problem
public class MyArrayException extends Exception{
public MyArrayException()
{super();}
public MyArrayException(String s)
{super(s);}
public String getMessage(){
System.out.println(Oops you cant add the arrays);
return super.getMessage();
}}
-
8/3/2019 L14 Exception
35/37
Now, rewrite the function
public static int [] add(int [] n1, int [] n2)
throws MyArrayException {
if (n1.length ! = n2.length)
throw new MyArrayException(Wrong!);else {
int [] n3 = new int[n1.length];
for (int k = 0; k
-
8/3/2019 L14 Exception
36/37
So, what will happen here?
int [] a = { 3, 5, 6};
int [] b = { 4, 9};
try {
int [] c = MyArrayTest.add(a, b);
}
catch (MyArrayException e) {System.out.println(e.getMessage());
}
-
8/3/2019 L14 Exception
37/37
The Output
Oops you cant add the arrays
Wrong!