MIT AITI 2003 Lecture14 Exceptions

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
Exceptions CIS 304 Intermediate Java Programming for Business.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Object Throwable ErrorException RuntimeException.
Java Exceptions a quick review….
Chapter 14 – Exception Handling
Exceptions In this lecture:
Exceptions: When things go wrong
Chapter 10 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Handling Exceptionally Sticky Problems
Chapter 13 Exception Handling
Introduction to Exceptions in Java
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
CS102 – Exceptions David Davenport Latest: May 2015
COMPSCI 230 S Programming Techniques
CSE 501N Fall ’09 17: Exception Handling
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Handling Exceptions.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exception Handling Chapter 9.
ATS Application Programming: Java Programming
Exceptions & exception handling
Exception Handling in Java
Exception Handling and Reading / Writing Files
Exception Handling Chapter 9 Edited by JJ.
Lecture 9: Exceptions in Java CS201j: Engineering Software
Web Design & Development Lecture 7
Chapter 13 Exception Handling
Java Exceptions Dan Fleck CS211.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Tutorial Exceptions Handling.
Chapter 12 Exception Handling and Text IO Part 1
Handling Exceptionally Sticky Problems
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exceptions 10-May-19.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Java Basics Exception Handling.
CMSC 202 Exceptions.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

MIT AITI 2003 Lecture14 Exceptions Java’s Error handling mechanism

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

SampleProgram (1) -- What’s 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]); }

SampleProgram (2) --The output java.lang.ArrayIndexOutOfBoundsException at SampleProgram.main(SampleProgram.java:5) Exception in thread "main"

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 user – you have used an array element that isn’t within the array’s boundaries. ArrayIndexOutOfBoundException is a subclass of Exception

Some words about Exceptions All exceptions are subclasses of Exception. Some exceptions are comparable to compiler errors, e.g. ArrayIndexOutOfBoundsException Others must be dealt with every time a program runs – you can’t 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

SumNumbers (1) public class SumNumbers { public static void main(String[] arguments) { float sum = 0; for (int i=0; i<arguments.length; i++) sum += Float.parseFloat(arguments[i]); System.out.println("Those numbers add up to "+ sum); }

SumNumbers (2) java SumNumbers 8 6 7 5 3 0 9 Output: Those numbers add up to 38.0 Java SumNumbers 1 3 5x Output?

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"

Catching Exceptions in a try-catch Block

NewSumNumbers – (1) public class NewSumNumbers { public static void main(String[] arguments) { float sum = 0; for (int i=0; i<arguments.length; i++) try { sum += Float.parseFloat(arguments[i]); } catch (NumberFormatException e) { System.out.println(arguments[i] + " is not a number."); System.out.println("Those numbers add up to "+ sum);

NewSumNumbers – (2) Java NewSumNumbers 1 3 5x Output: 5x is not a number. Those numbers add up to 4.0

NewSumNumbers – (3) A try-catch block can be used with any exception that you want a program to handle try{ //statement(s) that might cause the exception } catch (Exception e) { //what to do when the exception occurs

Catching Several Different Exceptions

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");

Handling Something After an Exception

try-catch-finally block //statement(s) that might cause the exception } catch (Exception e) { //what to do when the exception occurs finally { //statements to execute no matter what

Throwing Exceptions

When a method throws an exception… NetReader.java:14: unreported exception java.net.MalformedURLException; must be caught or declared to be thrown This indicates that you are trying to use a method that throws an exception. You must do one of the following things: Handle the exception with a try-catch block Throw the exception Handle the exception with a try-catch block and then throw it.

Handle the exception with a try-catch block public class NewSumNumbers { public static void main(String[] arguments) { float sum = 0; for (int i=0; i<arguments.length; i++) try { sum += Float.parseFloat(arguments[i]); } catch (NumberFormatException e) { System.out.println(arguments[i] + " is not a number."); System.out.println("Those numbers add up to "+ sum); }

Handle the exception with a try-catch block and then throw it public class NewSumNumbers { public static void main(String[] arguments) throws NumberFormatException { float sum = 0; for (int i=0; i<arguments.length; i++) try { sum += Float.parseFloat(arguments[i]); } catch (NumberFormatException e) { System.out.println(arguments[i] + " is not a number."); throw e; System.out.println("Those numbers add up to "+ sum); }

Create your own exception class

Writing Your Own Exception Classes Writing your own exception class is simple. New exception classes allow you to handle a new type of error separately. Exception classes extend java.lang.Exception. public class DataFormatException   extends java.lang.Exception {     public DataFormatException() { super(); }     public DataFormatException(String s)     { super( s ); } }

Exception Objects -Structure 2 Constructors the default constructor with no argument the constructor that takes a string (error message) argument getMessage() method return the error message string (the argument of the 2nd constructor)

Creating and Throwing your own Exception instances Exceptions are objects. You must create a new instance of an exception before you can throw it     if ( dArray.length == 0 )     throw new IllegalArgumentException();

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 or Error. These are called checked exceptions (checked by the compiler). Exceptions derived from RuntimeException are called unchecked exceptions and their declaration is optional.

Throwing an Exception -- An Example public 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;   } }

Exceptions, Errors, and RuntimeExceptions Throwable have two special subclasses: Error and Exception Error: a catastrophic failure (your program will not be able to recover) Exception: a non-catastrophic failure (your program should recover or exit gracefully) RuntimeException (unchecked Exception): a special subclass of Exception. Methods and constructors throwing RuntimeExceptions do not have to declare this fact. All other exceptions (checked exception): methods or constructors throwing checked exception should declare this fact.

Checked vs. Unchecked Exceptions In principle, checked exceptions are those which you, the programmer, are supposed to be able to fix at runtime, such as a FileNotFoundException. Very often these are generated in system code by user, not programmer error. Unchecked exceptions (RuntimeExceptions) are supposed to be able to occur anywhere (so hard to check for) and to be the result of programmer error (so the best way of handling them is to fix the program). Good examples of unchecked exceptions: NullPointerException, ArrayIndexOutOfBoundsException. Bad example of unchecked exceptions, NumberFormatException, thrown e.g. by Float.parseFloat(String s).

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

Expecting the unexpected types 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 Java’s exception handling mechanism.

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 don’t match the signature of the methods.

What’s wrong here? public static int [] add(int [] n1, int [] n2) { int [] n3 = new int[n1.length]; for (int k = 0; k<n1.length; k++) n3[k] = n1[k]+n2[k]; return n3; }

Let’s 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(); }

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<n1.length; k++) n3[k] = n1[k]+n2[k]; return n3; }

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());

The Output… Oops you cant add the arrays Wrong!