Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in.

Slides:



Advertisements
Similar presentations
Exceptions Session 21. Memory Upload Creating Exceptions Using exceptions to control object creation and validation.
Advertisements

Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
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.
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.
MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
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.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
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.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
©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.
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]);
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
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
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.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
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.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
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.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
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.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
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. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
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.
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 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.
Web Design & Development Lecture 7
Lecture 11 Objectives Learn what an exception is.
Tutorial Exceptions Handling.
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.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Exceptions 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.

Introduction THROWS an exception If an error occurs Java run-time environment

Pre-defined exception classes in Java Throwable NumberFormatException ArrayIndexOutOfBoundsException FileNotFoundException Exception Error RuntimeException IOException IllegalArgumentException IndexOutOfBoundsException

Checked and unchecked exceptions Java Compiler RuntimeException NumberFormatException IOException FileNotFoundException ERROR

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 } } A program that allows a user to enter an aptitude test mark at the keyboard.

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); SSystem.in may throw a checked IOException

Dealing with exceptions Whenever a method that throws a checked exception, the Java compiler insists that we acknowledge this exception in some way. There are always two ways to deal with an exception: 1.Deal with the exception within the method by catching it; 2.Pass on the exception out of the method by claiming it.

Claiming an exception Claiming an exception refers to a given method having been marked to indicate that it will pass on an exception object that it might generate. 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 } }

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

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"); } } } Fixing the problem

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

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. method throw Exception catch Exception

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 TestException { private static int getInteger( ) throws IOException { byte [] buffer = new byte[512]; System.in.read(buffer); String s = new String (buffer); s = s.trim(); int num = Integer.parseInt(s); return num; }

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 not be a valid array size This would cause an exception in the program; The name of the exception is NegativeArraySizeException.

Making use of exceptions: a first attempt public Bank(int sizeIn) throws NegativeArraySizeException { list = new BankAccount[sizeIn]; total = 0; }

Making use of exceptions: a second attempt public Bank (int sizeIn) throws Exception { if (sizeIn < 0) { throw new Exception ("cannot 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 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 NegativeSizeException { if (sizeIn < 0) { throw new NegativeSizeException(); } else { list = new BankAccount[sizeIn]; total = 0; } }

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(); } // other static methods here as before } }

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

Documenting exceptions /** Creates an empty collection of bank accounts * and fixes the maximum size of this collection * sizeIn The maximum size of *the collection of bank * accounts NegativeSizeExceptionIf the collection is *sized with a negative *value */ public Bank (int sizeIn) throws NegativeSizeException { // as before }