Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.

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

CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
COMP 121 Week 5: Exceptions and Exception Handling.
Exception Handling By: Thomas Fasciano. What is an Exception?  An error condition that occurs during the execution of a Java Program.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
COMP201 Java Programming Topic 6: Exceptions Reading: Chapter 11.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
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 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.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exception Handling Recitation – 10/(23,24)/2008 CS 180 Department of Computer Science, Purdue University.
Exception Handling (Chapter 8) CS 180 Recitation - February 29, 2008 Department of Computer Science Purdue University.
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.
Introduction to Computer Programming Error Handling.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
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.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
COMP Exception Handling Yi Hong June 10, 2015.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
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 in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
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 Advanced Flow of Control : Introduction This chapter focuses on: –exception processing –catching and handling exceptions –creating new exceptions –exception.
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
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 Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
Exceptions and Assertions Chapter 15 – CSCI 1302.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
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.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
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.
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.
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.
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Testing and 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.
EE422C Software Implementation II
Exception Handling.
CMSC 202 Exceptions 2nd Lecture.
Exception Handling in Java
Web Design & Development Lecture 7
Lecture 11 Objectives Learn what an exception is.
CMSC 202 Exceptions 2nd Lecture.
Chapter 12 Exception Handling and Text IO Part 1
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:

Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming

SE15: Exceptions27–2 Today’s Learning Objectives For you to appreciate why exceptions are a useful mechanism for signalling errors in programs For you to understand the effect of exceptions on flow of control in a program For you to see how we can intercept exceptions that occur within Java code

SE15: Exceptions27–3 Lecture Outline Traditional approaches to error handling A different approach: exceptions Flow of control Dealing with exceptions

SE15: Exceptions27–4 Traditional Approaches To Error Handling Ignore it! Caller should do the right thing Terminate the program Call System.exit Transfer responsibility

SE15: Exceptions27–5 Example: Ignoring Errors class Date { private int day, month, year;... public void setMonth(int theMonth) { month = theMonth; } }

SE15: Exceptions27–6 Example: Program Termination class Date { private int day, month, year;... public void setMonth(int theMonth) { if (theMonth 12) { System.err.println("Invalid month!"); System.exit(1); } month = theMonth; } }

SE15: Exceptions27–7 What Do You Think? What is wrong with this approach? Where would it be reasonable to use it?

SE15: Exceptions27–8 Transfer Responsibility class Date { private int day, month, year;... public boolean setMonth(int theMonth) { if (theMonth >= 1 && theMonth <= 12) { month = theMonth; return true; } else return false; } }

SE15: Exceptions27–9 Dealing With Returned Value do { String input = JOptionPane.showInputDialog(...); int month = Integer.parseInt(input); } while (! date.setMonth(month)); String input = JOptionPane.showInputDialog(...); int month = Integer.parseInt(input); date.setMonth(month);... We should do something like this: …but we are allowed to do this:

SE15: Exceptions27–10 Problems Class author May not be able to return a boolean from a method Class user Other code may ‘swallow up’ the return value

SE15: Exceptions27–11 The Solution: Exceptions Build on the idea of transferring error-handling responsibility to a context better able to deal with it Not the same as returning an error value Exceptions change flow of control Exceptions cannot be ignored Two aspects Signalling the error by throwing an exception Dealing with the error by catching the exception

SE15: Exceptions27–12 Exceptions in Java Exceptions are objects, containing Variables to provide information on the error Methods to access that information Two types Unchecked ArrayIndexOutOfBoundsException NullPointerException NumberFormatException Checked FileNotFoundException

SE15: Exceptions27–13 Flow of Control After an exception is thrown, normal flow of program execution is suspended JVM looks for an exception handler in the method If there is no handler in the method, the exception moves up to the caller of the method… Eventually, exception can end up in main If main doesn’t handle it, the program is halted

SE15: Exceptions27–14 Flow of Control public static void main(String[] args) { foo(); } public static void foo() { bar(); System.out.println("Foo!"); } public static void bar() { int impossibleResult = 1/0; System.out.println(impossibleResult); } ArithmeticException occurs here… …and propagates to here… …then to here, where it halts program These don’t execute!

SE15: Exceptions27–15 Dealing With Exceptions Put code that might throw an exception in a try block Add one or more catch blocks to match the types of exception that could be thrown Write code inside the catch blocks Print an error message Log details of error to a file Fix the problem! Never ‘swallow’ exceptions with empty catch blocks!

SE15: Exceptions27–16 Example try { Scanner keyboard = new Scanner(System.in); System.out.print("Enter numerator: "); int n = keyboard.nextInt(); System.out.print("Enter denominator: "); int d = keyboard.nextInt(); int result = n/d; System.out.println("Result = " + result); } catch (ArithmeticException error) { System.err.println("Division by zero!"); }

SE15: Exceptions27–17 Catching Exceptions in main Often a good idea Gives us control of how the program terminates public static void main(String[] args) { try {... } catch (Exception error) { error.printStackTrace(); //System.err.println(error); System.exit(1); } } Intercepts everything! Prints full details Prints simple error message

SE15: Exceptions27–18 Summary We have Seen that traditional approaches to error handling are either too inflexible or too easily ignored Considered how exceptions can solve these problems Examined how flow of control within a program changes when an exception is thrown Looked at examples of Java exceptions Discussed how to intercept exceptions in Java programs