Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.

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

AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Topics Introduction Types of Errors Exceptions Exception Handling
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
CS102--Object Oriented Programming
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
1 Handling Exceptions COSC 1567 C++ Programming Lecture 11.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
TCU CoSc Programming with Java Handling Exceptions.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
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.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
True or false A variable of type char can hold the value 301. ( F )
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions CIS 304 Intermediate Java Programming for Business.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
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.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
1 Chapter Eight Exception Handling. 2 Objectives Learn about exceptions and the Exception class How to purposely generate a SystemException Learn about.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
The Java Programming Language
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects CS 146 Class Notes Fall 10.
Exception. Runtime Error Consider the following program: public class BadArray { public static void main(String[] args) { // Create an array with three.
COMP Exception Handling Yi Hong June 10, 2015.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 8 Scope of variables Name reuse. Scope The region of program code where it is legal to reference (use) a variable The scope of a variable depends.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
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.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
Exceptions and Assertions Chapter 15 – CSCI 1302.
Error Handling Tonga Institute of Higher Education.
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
Chapter 8-Exception Handling/ Robust Programming.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
JavaScript and Ajax (Control Structures) Week 4 Web site:
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception Handling How to handle the runtime errors.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
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.
Section 3.3 Exceptional Situations. 3.3 Exceptional Situations Exceptional situation Associated with an unusual, sometimes unpredictable event, detectable.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Chapter 10 – Exception Handling
Testing and Debugging.
CMSC 202 Exceptions 2nd Lecture.
CSC 143 Java Errors and Exceptions.
Exceptions 10-May-19.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions.
Presentation transcript:

Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities

An exception = something has gone wrong – an error has occurred – not a good thing Examples: the use was asked to input a size (numeric) and put in a name (string) The program could: –Quit and return to the operating system –Ignore the input –Display a help message

Another example: an attempt to load a file It cannot be found (possible responses – same as last example) Attempt to print and out of paper –Some printer software examines the status and will indicate out of paper condition

Why do we need error notification? How is it provided? Software and hardware systems in Java are pre-packaged (classes and methods) we don’t care how they work internally – but – vital we are informed of error conditions Software may be set up to detect errors and take alternative action. Some errors handled locally – more serious are passed “upstairs.”

A printer runs out of paper… Normally a technician refills the printer but what if the organization is out – a manager may need to be informed. A technician trips on a cable and breaks a leg (possible legal action) Should be handled by a managing director. Analogy: a person doing a job and a method when a error occurs. Java exception facilities allow us to set up a plan of action. If something wrong – handle the problem else handle the normal situation.

Given: do A(); do B(); do C(); Becomes: – do A(); if ( do A() went wrong) handle the do A() problem – else do B(); – if ( do B() went wrong) handle the do B() problem – else do C(); if ( do C() went wrong) handle the do C() problem – else …

If an error condition occurs (we do not want it to occur) Java exception facilities allow us to code the normal and the exceptional use Java methods can only pass back a single result

Exceptions and objects Boolean variables are not always the answer as to when an error occurs: boolean errorhappened = false; … code whichaffects errorCase – if (errorHappened = = true ) { –… handle problem …

This is not how errors are indicated by Java We use the object approach. We use ‘new’ to create an instance of the appropriate exception class. Another region of the program may check for the errors existance An instance of the exception class is created to indicate “an error happened”

When to use exceptions Exceptions provide a control structure –When should we use them? Rather than an if statement or while loop. Example: we wish to add a series of positive numbers and end the series with a -1. That is not the exception. (it is normal input) We use exception handling for errors not normal input.

The jargon of exceptions – Java’s own terminology throws, throw, try, catch and finally are keywords that carry out the task or error detection. A try – catch example program: ExceptionDemo1 pages “a number doubling program” User inputs an integerr and program doubles it and displays the answer in another field. If the user inputs something ‘not a number’ the ‘parseInt method will not be able to process it. Screen shot page 302 shows ‘good’ integer and doubles it. ‘bad’ integer ‘xx’ blanks the output field and error message

Key part of program try {int number = Integer.parseInt (inputField.setText (Integer.toString( 2 * number)) } catch (Number FormatException errorObject) { JOptionPane.showMessageDialog (null, “Error in number retype” ); }

The ‘new’ statement: general form try { a series of statements } cach (some exception errorObject) { handle the exception;} A Java block { } all statement within curly braces Execute statements in the try block if no error catch block ignored. If error occurs catch block is executed.

catch (NumberFormatException errorObject) similar to a methos declaration. parseInt may throw a NumberFormatException if it does catch block will execute. –Catch (NumberFormatException errorObject) { OPtionPane.showMessageDialog (null, “Error “ + errorObject.toString ( ) );} –// returns the name of the exception

private void aMethod ( ) { – try { // some code …} – catch (Exception errorObject) {handle it} –return

try and scope When a try block produces an exception – execution terminates – variables declared within it become inaccessible (can not be used in catch block) They must be declared outside the try block

String s; try { code involving s…} catch (exception errorObject) { – JOptionPane.showMessageDialog ( null, “Error: s is “ + s);}