1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.

Slides:



Advertisements
Similar presentations
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Advertisements

Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Yoshi
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
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.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
Review Linked list: Doubly linked list, insertback, insertbefore Remove Search.
C# Programming: From Problem Analysis to Program Design1 Debugging and Handling Exceptions C# Programming: From Problem Analysis to Program Design 3 rd.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
Mahmoud Rafeek Alfarra Computer Programming || Chapter 2: Exception handling.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
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 (Large parts of these copied from Ed Schonberg’s slides)
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exception Handling An Exception is an indication of a problem that occurs during a program’s execution. Exception handling enables the programmer to create.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
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.
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.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Exceptions Syntax, semantics, and pragmatics Exceptions1.
Exceptions Handling the unexpected. RHS – SWC 2 The Real World So far, most of our code has been somewhat näive We have assumed that nothing goes wrong…
Exceptions Handling Exceptionally Sticky Problems.
VB.Net - Exceptions Copyright © Martin Schray
Introduction to Exception Handling and Defensive Programming.
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
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.
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.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
1 Chapter 15 Exceptions and Assertions. 2 Objectives F To know what is exception and what is exception handling (§15.2). F To distinguish exception types:
Exception Handling SWE 344 Internet Protocols & Client Server Programming.
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.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Lecture 11 Dr. Eng. Ibrahim El-Nahry Exception Handling.
Why exception handling in C++?
Creating and Modifying Text part 2
Testing and Exceptions
Advanced Programming Behnam Hatami Fall 2017.
EE422C Software Implementation II
ATS Application Programming: Java Programming
Abdulmotaleb El Saddik University of Ottawa
Exception Handling in Java
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Exceptions handling Try, catch blocks Throwing exceptions.
Chapter 13 Exception Handling: A Deeper Look
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Java Basics Exception Handling.
Presentation transcript:

1 Handling Errors and Exceptions Chapter 6

2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise exceptions from your own methods using the throw keyword. 3. Enable checking for integer overflow.

3 Error Processing The old way: Do Something; if (Error) { Take some action to handle error; }

4 Problems with the old way: New error overwrites old one. Error checking clutters the code. Makes the normal code hard to read Error codes such as -1 are not inherently meaningful. To use a function you have to know its error codes. No built-in error messages Easy to ignore errors.

5 Exceptions Exceptions are the modern solution to error handling. Rare example of a “good goto” Rather than completing and returning an error code when somthing goes wrong, “goto” to the caller’s error handling routine. Can propagate up the call stack.

6 When to Use Exception Handling Use an exception handler for unexpected problems Bad data Impossible condition Not for normal flow of control End of loop End of file Exception processing is usually very slow.

7 Example: Catch Block static void Main(string[ ] args) { try { int lhs = Int32.Parse(Console.ReadLine()); int rhs = Int32.Parse(Console.ReadLine()); int ans = lhs / rhs; Console.WriteLine(ans.ToString()); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } Console.ReadLine(); // Hold window open }

8 Example: Divide by Zero

9 Example: Input not an integer

10 Example: Nonnumeric Input

11 Example: Value Out of Range

The exception will propagate upward if not handled. static int Divide (int lhs, int rhs) { int ans = lhs / rhs; return ans; } static void Main(string[] args) { try { int lhs = Int32.Parse(Console.ReadLine()); int rhs = Int32.Parse(Console.ReadLine()); int ans = Divide (lhs, rhs); Console.WriteLine(ans.ToString()); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } 2. Divide throws exception (No handler) 1. Call function (rhs == 0) 3. Continue here

13 Exception Propagates Upward

14 You can provide multiple catch handlers try { int lhs = Int32.Parse(Console.ReadLine()); int rhs = Int32.Parse(Console.ReadLine()); int ans = lhs / rhs; Console.WriteLine(ans.ToString()); } catch (System.FormatException ex) { Console.WriteLine("Please enter a integer value."); } catch (System.DivideByZeroException ex) { Console.WriteLine("Please enter a nonzero value for divisor."); }

15 Checked and Unchecked Integer Arithmetic By default, integer arithmetic is unchecked. Integer overflow will not throw an exception. Overflow checking can be enabled for an entire project individual blocks of codes individual expressions

16 Checked and Unchecked Integer Arithmetic static void Main(string[] args) { try { int lhs = Int32.Parse(Console.ReadLine()); int rhs = Int32.Parse(Console.ReadLine()); int ans = lhs + rhs; Console.WriteLine(ans.ToString()); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } Console.ReadLine(); // Hold window open }

17 Using Unchecked Integer Arithmetic

18 Using Checked Integer Arithmetic static void Main(string[] args) { try { int lhs = Int32.Parse(Console.ReadLine()); int rhs = Int32.Parse(Console.ReadLine()); int ans = checked(lhs + rhs); Console.WriteLine(ans.ToString()); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } Console.ReadLine(); // Hold window open }

19 Using Checked Integer Arithmetic

20 A Checked Block static void Main(string[] args) { checked { try { int lhs = Int32.Parse(Console.ReadLine()); int rhs = Int32.Parse(Console.ReadLine()); int ans = lhs + rhs; Console.WriteLine(ans.ToString()); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } Console.ReadLine(); // Hold window open }

21 Checked Compiler Option To set the compiler option, right click on the project in Solution Explorer and select Properties. Then click the Advanced button

22 Checked Compiler Option Click here

23 Checked Compiler Option Now all integer arithmetic in this project will be checked. Click OK

24 Unchecked Source Code static void Main(string[] args) { try { int lhs = Int32.Parse(Console.ReadLine()); int rhs = Int32.Parse(Console.ReadLine()); int ans = lhs + rhs; Console.WriteLine(ans.ToString()); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } Console.ReadLine(); // Hold window open }

25 Overflow Exception

This is how you can return an error indication to the caller. Example: public static string monthName(int Month) { switch (Month) { case 1 : return "January"; case 2 : return "February"; //... case 12 : return "December"; default : throw new ArgumentOutOfRangeException("Bad Month"); } } Throwing Exceptions Class defined in the System namespace Creates an object of class ArgumentOutOfRangeException having error message “Bad Month”.

27 Why throw an exception? Library functions know what is wrong but not what to do about it. Clients know what to do but may not know what is wrong. Various clients may respond to error conditions in different ways. Library function throws an exception. Client handles it.

28 Writing a finally block Sometimes you need to be sure that some cleanup code is executed even if an exception is thrown and your method does not run to completion. string line; StreamReader reader = new while ((line = reader.ReadLine()) != null) { // Do something with line. // May result in an exception. } reader.Close();

29 Writing a finally block If something goes wrong in the while loop and an exception is thrown, the close will not be executed. You can use a finally block to ensure that the close is executed even if an exception is thrown.

30 Writing a finally block StreamReader reader; try { string line; reader = new while ((line = reader.ReadLine()) != null) { // Do something with line. // May result in an exception. } finally { if (reader != null) { reader.Close(); }

31 Writing a finally block Use “finally” after a “try” block for something that must be done whether or not an exception is thrown. Typically releasing resources. “finally” block goes after last “catch” block (if any)

32 Executing the finally block If an exception is thrown in the try block and caught locally “finally” block is executed after the catch block. and not caught locally “finally” block is executed before the exception is propagated upward. If no exception is thrown in the try block “finally” block is executed after the try block.

33 Summary Exception handling is an effective mechanism for dealing with errors. Supports error recovery when possible. Permits detailed, meaningful error messages. Gets error processing out of the way. Use exception handlers for unexpected problems. Not for normal “errors” such as end of file.

34 Handling Errors and Exceptions Assignment: Read Chapter 6 Project 1 End of Presentation