MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Slides:



Advertisements
Similar presentations
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Advertisements

Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
Java Exceptions. Exceptions Often in computing, operations cannot properly execute because some sort of error has occurred. Some examples: Often in computing,
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
For use of Cleveland State's IST410 Students only 1 Exception.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException.
Java Programming Exceptions. Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
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.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
Exception handling Dealing with life’s little surprises.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exceptions Handling.
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.
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
CS1020 Data Structures and Algorithms I Lecture Note #6 Exceptions Handling exceptional events.
Java Exception Handling Handling errors using Java’s exception handling mechanism.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Java Software Solutions Foundations of Program Design Sixth Edition
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Preventing and Correcting Errors
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Program Errors Syntax errors Logic errors
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
Class Design: Handling Errors Reading: 2 nd Ed: Chapter 15 3 rd Ed: Chapter 11 Exercises 2 nd Ed: P15.5, P15.6 (Hint: look at documentation for Scanner.
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in.
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.
1 Advanced Flow of Control : Introduction This chapter focuses on: –exception processing –catching and handling exceptions –creating new exceptions –exception.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exceptions and Assertions Chapter 15 – CSCI 1302.
1 1. Normal and exceptional control flow 2. Java exception types 3. Exception handling syntax 4. Inheritance.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
LECTURE 8: EXCEPTIONS CSC 212 – Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May.
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.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
© 2001 by Ashby M. Woolf Revision 2 Exceptions for Exceptional Circumstances Passing a Problem up the Chain of Command.
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Introduction to OO Program Design
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.
ATS Application Programming: Java Programming
Web Design & Development Lecture 7
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Exception Handling Contents
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.
Java Basics Exception Handling.
Presentation transcript:

MSc IT Programming Methodology (2)

THROWS an EXCEPTION Errors?

By the end of this lecture you should be able to: explain the term exception distinguish between checked and unchecked exception classes in Java claim an exception using a throws clause throw an exception using a throw command catch an exception in a try catch block; define and use your own exception classes. Exceptions

Pre-defined exception classes in Java

Throwable

Exception Error

Throwable Exception Error RuntimeException IOException

Throwable FileNotFoundException Exception Error RuntimeException IOException

Throwable FileNotFoundException Exception Error RuntimeException IOException IllegalArgumentException IndexOutOfBoundsException

Throwable NumberFormatException FileNotFoundException Exception Error RuntimeException IOException IllegalArgumentException IndexOutOfBoundsException

Throwable NumberFormatException ArrayIndexOutOfBoundsException FileNotFoundException Exception Error RuntimeException IOException IllegalArgumentException IndexOutOfBoundsException

Throwable NumberFormatException ArrayIndexOutOfBoundsException FileNotFoundException Exception Error RuntimeException IOException IllegalArgumentException IndexOutOfBoundsException Unchecked

Throwable NumberFormatException ArrayIndexOutOfBoundsException FileNotFoundException Exception Error RuntimeException IOException IllegalArgumentException IndexOutOfBoundsException Unchecked

Throwable NumberFormatException ArrayIndexOutOfBoundsException FileNotFoundException Exception Error RuntimeException IOException IllegalArgumentException IndexOutOfBoundsException Checked

Java Compiler RuntimeException NumberFormatException IOException FileNotFoundException WARNING!

Handling exceptions: an example

public class AptitudeTest { public static void main (String[] args) { int score; System.out.print("Enter aptitude test score: "); score = TestException.getInteger( ); // test score here } } Let’s look at the code for this method.

Outline TestException class public class TestException { public static int getInteger() { // code for method goes here } }

The read method of System.in

"hello" System.in.read( [ ] ) array of bytes 104,101,108, 111,13,10

Coding the getInteger method

This is a first attempt, it will not compile! byte [] buffer = new byte[512]; System.in.read(buffer); String s = new String (buffer); s = s.trim(); int num = Integer.parseInt(s); return num; System.in.read(buffer); TThe read method may throw a checked IOException

Dealing with exceptions..

main getInteger read

main getInteger read IOException!

main getInteger read catch

main getInteger read IOException!

main getIntegerread throw

main getInteger IOException! read throw

main getInteger IOException! read

main getIntegerread catch

main getInteger IOException! read

maingetIntegerread throw

main IOException! getIntegerread throw

Claiming an exception

To claim an exception we add a throws clause to our method header import java.io.* public class TestException { private static int getInteger( ) throws IOException { // as before } } This method will pass on the IOException error.

Revisiting the AptitudeTest class public class AptitudeTest { public static void main (String[] args) { int score; System.out.print("Enter aptitude test score: "); score = TestException.getInteger( ); // test score here } } score = TestException.getInteger( );

main IOException! getIntegerread throw

main IOException! getIntegerread

main getIntegerread catch

main IOException! getIntegerread

maingetIntegerread throw PROGRAM CRASH!!!!

import java.io.*; public class AptitudeTest { public static void main (String[] args) throws IOException { int score; System.out.print("Enter aptitude test score: "); score = TestException.getInteger( ); if (score >= 50) { System.out.println("You have a place on the course!"); } else { System.out.println("Sorry, you failed your test"); } } }

A test run Enter aptitude test score: java.lang.NumberFormatException: 12w at java.lang.Integer.parseInt(Integer.java:418) at java.lang.Integer.parseInt(Integer.java:458) at TestException.getInteger(TestException.java:10) at AptitudeTest.main(AptitudeTest.java:11) 12w

Enter aptitude test score: java.lang.NumberFormatException: 12w at java.lang.Integer.parseInt(Integer.java:418) at java.lang.Integer.parseInt(Integer.java:458) at TestException.getInteger(TestException.java:10) at AptitudeTest.main(AptitudeTest.java:11) 12w A Stack Trace

NumberFormatException byte [] buffer = new byte[512]; System.in.read(buffer); String s = new String (buffer); s = s.trim(); int num = Integer.parseInt(s); return num; int num = Integer.parseInt(s);

Catching an exception. In order to trap the exception object in a catch block you must surround the code that could generate the exception in a try block.

Syntax for using a try and catch block try { // code that could generate an exception } catch (Exception e) { // action to be taken when an exception occurs } // other instructions could be placed here

Some methods of the Exception class methoddescription printStackTrace prints (onto the console) a stack trace of the exception toString returns a detailed error message getMessage returns a summary error message

import java.io.*; public class AptitudeTest2 { public static void main (String[ ] args) { try { // as before score = TestException.getInteger( ); // as before } catch (NumberFormatException e) { System.out.println("You entered an invalid number!"); } catch (IOException e) { System.out.println(e); } System.out.println("Goodbye"); } }

Test Run of ApititudeTest2 Enter aptitude test score:12w You entered an invalid number! Goodbye

import java.io.*; public class AptitudeTest2 { public static void main (String[ ] args) { try { // as before score = TestException.getInteger( ); // as before } catch (NumberFormatException e) { System.out.println("You entered an invalid number!"); } catch (IOException e) { System.out.println(e); } System.out.println("Goodbye"); }

import java.io.*; public class AptitudeTest2 { public static void main (String[ ] args) { try { // as before score = TestException.getInteger( ); // as before } catch (NumberFormatException e) { System.out.println("You entered an invalid number!"); } catch (IOException e) { System.out.println(e); } System.out.println("Goodbye"); } Generates a NumberFormatException

import java.io.*; public class AptitudeTest2 { public static void main (String[ ] args) { try { // as before score = TestException.getInteger( ); // as before } catch (NumberFormatException e) { System.out.println("You entered an invalid number!"); } catch (IOException e) { System.out.println(e); } System.out.println("Goodbye"); }

import java.io.*; public class AptitudeTest2 { public static void main (String[ ] args) { try { // as before score = TestException.getInteger( ); // as before } catch (NumberFormatException e) { System.out.println("You entered an invalid number!"); } catch (IOException e) { System.out.println(e); } System.out.println("Goodbye"); }

import java.io.*; public class AptitudeTest2 { public static void main (String[ ] args) { try { // as before score = TestException.getInteger( ); // as before } catch (NumberFormatException e) { System.out.println("You entered an invalid number!"); } catch (IOException e) { System.out.println(e); } System.out.println("Goodbye"); }

Exceptions in GUI applications room should be a number

Using exceptions in your own classes

Look back at the Bank constructor: public Bank(int sizeIn) { list = new BankAccount[sizeIn]; total = 0; } A negative value would cause a NegativeArraySizeException.

Making use of exceptions: a first attempt

public Bank(int sizeIn) throws NegativeArraySizeException { list = new BankAccount[sizeIn]; total = 0; } Reveals that we are using an array.

Making use of exceptions: a second attempt

public Bank (int sizeIn) throws Exception { if (sizeIn < 0) { throw new Exception ("can’t set a negative size"); } else { list = new BankAccount[sizeIn]; total = 0; } }

Testing for the exception

public class BankProgram { public static void main(String[] args) { try { System.out.print(“Maximum number of accounts?“); size = EasyScanner.nextInt(); Bank myBank = new Bank(size); // rest of code here } catch (Exception e) { System.out.println(e.getMessage()); } } // other static methods here as before

Creating your own exception classes

Throwable NumberFormatException ArrayIndexOutOfBoundsException FileNotFoundException Exception Error RuntimeException IOException IllegalArgumentException IndexOutOfBoundsException

Throwable NumberFormatException ArrayIndexOutOfBoundsException FileNotFoundException Exception Error RuntimeException IOException IllegalArgumentException IndexOutOfBoundsException NegativeSizeException

public class NegativeSizeException extends Exception { public NegativeSizeException () { super("cannot set a negative size"); } public NegativeSizeException (String message) { super (message); } }

Amending the Bank constructor

public Bank (int sizeIn) throws Exception { if (sizeIn < 0) { throw new Exception(); } else { list = new BankAccount[sizeIn]; total = 0; }

public Bank (int sizeIn) throws NegativeSizeException { if (sizeIn < 0) { throw new Exception(); } else { list = new BankAccount[sizeIn]; total = 0; }

public Bank (int sizeIn) throws NegativeSizeException { if (sizeIn < 0) { throw new NegativeSizeException(); } else { list = new BankAccount[sizeIn]; total = 0; }

Testing for the NegativeSizeException

public class BankProgram { public static void main(String[] args) { try { System.out.print(“Maximum number of accounts? “); size = EasyScanner.nextInt(); Bank myBank = new Bank(size); // rest of code here } catch (NegativeSizeException e) { System.out.println(e.getMessage()); System.out.println(“due to error in Bank constructor”); } catch (Exception e) { System.out.println(“Some unforseen error”); e.printStackTrace(); } // rest of code here } }

Re-throwing exceptions

public Bank (int sizeIn) throws NegativeSizeException { if (sizeIn < 0) { throw new NegativeSizeException(); } else { list = new BankAccount[sizeIn]; total = 0; }

public Bank (int sizeIn) throws NegativeSizeException { if (sizeIn ≥ 0) { throw new NegativeSizeException(); } else { list = new BankAccount[sizeIn]; total = 0; }

public Bank (int sizeIn) throws NegativeSizeException { if (sizeIn ≥ 0) { list = new BankAccount[sizeIn]; total = 0; } else { throw new NegativeSizeException(); }

public Bank (int sizeIn) throws NegativeSizeException { try { list = new BankAccount[sizeIn]; total = 0; } catch ( ? ) { throw new NegativeSizeException(); }

public Bank (int sizeIn) throws NegativeSizeException { try { list = new BankAccount[sizeIn]; total = 0; } catch ( NegativeArraySizeException e ) { throw new NegativeSizeException(); }

Practical Work

public class Exceptions { public static void main(String[ ] args) { int[ ] someArray = {12,9,3,11}; int position = getPosition(); display (someArray, position); System.out.println("End of program" ); } private static int getPosition() { System.out.println("Enter array position to display"); String positionEntered = EasyScanner.nextString(); return Integer.parseInt(positionEntered); } private static void display (int[ ] arrayIn, int posIn) { System.out.println("Item at this position is: " + arrayIn[posIn]); } } return Integer.parseInt(positionEntered); System.out.println("Item at this position is: " + arrayIn[posIn]); NumberFormatException ArrayIndexOutOfBoundsException

a)Re-write main so that it catches any exceptions it may now throw by displaying a message on the screen indicating the exception thrown.

public static void main(String[ ] args) { int[ ] someArray = {12,9,3,11}; int position = getPosition(); display (someArray, position); System.out.println("End of program" ); }

public static void main(String[ ] args) { try { int[ ] someArray = {12,9,3,11}; int position = getPosition(); display (someArray, position); } System.out.println("End of program" ); } // catches go here

b) Add an additional catch clause in main to catch any unaccounted for exceptions (within this catch clause print out the stack trace of the exception).

public static void main(String[ ] args) { try { int[ ] someArray = {12,9,3,11}; int position = getPosition(); display (someArray, position); } System.out.println("End of program" ); } // old catches as before

public static void main(String[ ] args) { try { int[ ] someArray = {12,9,3,11}; int position = getPosition(); display (someArray, position); } System.out.println("End of program" ); } // old catches as before // add additional catch clause Catches all exceptions not caught so far.

c) Create your own exception class InvalidPositionException (make this a checked exception).

public class InvalidPositionException { }

public class InvalidPositionException { } Make this a checked exception

public class InvalidPositionException { } extends Exception

public class InvalidPositionException { } extends Exception // add two constructors here

d)Re-write the display method so that it throws the InvalidPositionException from a catch block.

private static void display (int[ ] arrayIn, int posIn) { System.out.println("Item at this position is: " + arrayIn[posIn]); }

private static void display (int[ ] arrayIn, int posIn) throws InvalidPositionException { System.out.println("Item at this position is: " + arrayIn[posIn]); }

private static void display (int[ ] arrayIn, int posIn) throws InvalidPositionException { try { System.out.println("Item at this position is: " + arrayIn[posIn]); } catch ( ? ) { // code here }

e)Re-write main to take account of this amended display method.

public static void main(String[ ] args) { try { int[ ] someArray = {12,9,3,11}; int position = getPosition(); display (someArray, position); } System.out.println("End of program" ); } // old catches

public static void main(String[ ] args) { try { int[ ] someArray = {12,9,3,11}; int position = getPosition(); display (someArray, position); } System.out.println("End of program" ); } // modify catches so this new exception is caught