Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);

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)
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
COMP 121 Week 5: Exceptions and Exception Handling.
Chapter 9 Exception Handling. Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference.
Exception Handling Xiaoliang Wang, Darren Freeman, George Blank.
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.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
When you use an input or output file that does not exist, what will happen? −The compiler insists that we tell it what the program should do in such case.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Chapter 11.  Data is often stored in files such as a text file  We need to read that data into our program  Simplest mechanism  Scanner class  First.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
Final Review.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
Exception Handling. Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
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. 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.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
CS1020 Data Structures and Algorithms I Lecture Note #6 Exceptions Handling exceptional events.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
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:
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.
CS1101: Programming Methodology Recitation 3 – Control Structures.
Exception. Runtime Error Consider the following program: public class BadArray { public static void main(String[] args) { // Create an array with three.
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.
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.
Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Iteration. Java looping Options –while –do-while –for Allow programs to control how many times a statement list is executed.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
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.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
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.
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.
Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.
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.
The Problem Unexpected erroneous situations are often discovered by code which is NOT prepared to remedy the error………. For example.. String in = JOptionPane.showInputDialog(“enter.
Introduction to Exceptions in Java
Testing and Exceptions
CSE 501N Fall ’09 17: Exception Handling
Iteration.
مظفر بگ محمدی دانشگاه ایلام
Iteration.
مظفر بگ محمدی دانشگاه ایلام
Exception Handling.
Fundamental Error Handling
Lecture 11 Objectives Learn what an exception is.
Chapter 12 Exception Handling and Text IO Part 1
Exceptions.
Exceptions.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Exceptions

Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“); –Improper array subscripting int[] a = new int[3]; a[4] = 1000; –Improper arithmetic operations a[2] = 1000 / 0;

Java treatment of an exception If exception occurs and a handler is in effect –Flow of control is transferred to the handler –After handler completes flow of control continues with the statement following the handler If exception occurs and there is no handler for it –The program terminates

Task Prompt and extract the name of a file From that file, two integer values are to be extracted Compute and display the quotient of the values

Implementation public static void main(String[] args) throws IOException { Scanner stdin = new Scanner(System.in); System.out.print("Filename: "); String s = stdin.nextLine(); File file = new File(s); Scanner fileIn = new Scanner(file); int a = fileIn.nextInt(); int b = fileIn.nextInt(); System.out.println( a / b ); }

What can go wrong? public static void main(String[] args) throws IOException { Scanner stdin = new Scanner(System.in); System.out.print("Filename: "); String s = stdin.nextLine(); File file = new File(s); Scanner fileIn = new Scanner(file); int a = fileIn.nextInt(); int b = fileIn.nextInt(); System.out.println( a / b ); }

How can we deal with the problems? public static void main(String[] args) throws IOException { Scanner stdin = new Scanner(System.in); System.out.print("Filename: "); String s = stdin.nextLine(); File File = new File(s); Scanner fileIn = new Scanner(file);( int a = fileIn.nextInt()); int b = fileIn.nextInt()); System.out.println( a / b ); }

Exception handlers Code that might generate an exception is put in a try block –If there is no exception, then the handlers are ignored For each potential exception type there is a catch handler –When handler finishes the program continues with statement after the handlers try { Code that might throw exceptions of types E or F } catch (E e) { Handle exception e } catch (F f) { Handle exception f } More code

Introduce try-catch blocks public static void main(String[] args) throws IOException { Scanner stdin = new Scanner(System.in); System.out.print("Filename: "); String s = stdin.nextLine(); File file = new File(s); Scanner fileIn = new Scanner(file); int a = fileIn.nextInt(); int b = fileIn.nextInt()); System.out.println( a / b ); }

Setting up the file stream processing Scanner stdin = new Scanner(System.in); System.out.print("Filename: "); String s = stdin.nextLine(); // set up file stream for processing Scanner fileIn = null; try { File file = new File(s); fileIn = new Scanner(file); } catch (FileNotFoundException e) { System.err.println(s + “: Cannot be opened for reading"); System.exit(0); } How come the main() throws expression did not indicate it could throw a FileNotFoundException?

Getting the inputs try { int a = fileIn.nextInt(); int b = fileIn.nextInt(); System.out.println( a / b ); } catch (InputMismatchException e) { System.err.println(s + ": contains nonnumeric inputs"); System.exit(0); }

Converting the inputs try { int a = fileIn.nextInt(); int b = fileIn.nextInt(); System.out.println( a / b ); } catch (InputMismatchException e) { System.err.println(s + ": contains nonnumeric inputs"); System.exit(0); } catch (NoSuchElementException e) { System.err.println(s + ": does not contain two inputs"); System.exit(0); } catch (ArithmeticException e) { System.err.println(s + ": unexpected 0 input value"); System.exit(0); }

Run time exceptions Java designers realized –Runtime exceptions can occur throughout a program –Cost of implementing handlers for runtime exceptions typically exceeds the expected benefit Java makes it optional for a method to catch them or to specify that it throws them However, if a program does not handle its runtime exceptions it is terminated when one occurs

Commands type and cat Most operating systems supply a command for listing the contents of files –Windows: type –Unix, Linux, and OS X: cat type filename 1 filename 2 … filename n Displays the contents of filename 1 filename 2 … and filename n to the console window

Possible method main() for Type.java public static void main(String[] args) { for (int i = 0; i < args.length; ++i) { File file = new File(args[i]); Scanner fileIn = new Scanner(file); while (fileIn.hasNext()) { String s = fileIn.nextLine(); System.out.println(s); } fileIn.close(); } What can go wrong?

Use a finally block public static void main(String[] args) { for (int i = 0; i < args.length; ++i) { File fileIn = new File(args[i]); Scanner fileIn = new Scanner(file); while (fileIn.hasNext()) { String s = fileIn.nextLine(); System.out.println(s); } fileIn.close(); } File should be closed once its processing stops, regardless why it stopped

Use a finally block try { fileIn = null; File file = new File(args[i]); fileIn = new Scanner(file); while (fileIn.hasNext()) { String s = fileIn.nextLine(); System.out.println(s); } catch (FileNotFoundException e) { System.err.println(args[i] + ": cannot be opened"); } catch (IOException e) { System.err.println(args[i] + ": processing error"); } finally { if (fileIn != null) { filein.close(); } Always executed after its try-catch blocks complete

Exceptions Can create your exception types Can throw exceptions as warranted

Task Represent the depositing and withdrawing of money from a bank account What behaviors are needed –Construct a new empty bank account BankAccount() –Construct a new bank account with initial funds BankAccount(int n) –Deposit funds addFunds(int n) –Withdraw funds removeFunds(int n) –Get balance Int getBalance()

Sample usage public static void main(String[] args) Scanner stdin = new Scanner(System.in); BankAccount savings = new BankAccount(); System.out.print("Enter deposit: "); int deposit = stdin.nextInt()); savings.addFunds(deposit); System.out.print("Enter widthdrawal: "); int withdrawal = stdin.nextInt(); savings.removeFunds(withdrawl); System.out.println("Closing balance: " + savings.getBalance()); }

Task Represent the depositing and withdrawing of money from a bank account What behaviors are needed –Construct a new empty bank account BankAccount() –Construct a new bank account with initial funds BankAccount(int n) –Deposit funds addFunds(int n) –Withdraw funds removeFunds(int n) –Get balance int getBalance() What can go wrong?

Create a NegativeAmountException // Represents an abnormal bank account event public class NegativeAmountException extends Exception { // NegativeAmountException(): creates exception with // message s public NegativeAmountException(String s) { super(s); } Class Exception provides the exceptions behavior that might be needed Class NegativeAmountException gives the specialization of exception type that is needed

Sample usage public static void main(String[] args) throws IOException, NegativeAmountException { Scanner stdin = new Scanner(System.in); BankAccount savings = new BankAccount(); System.out.print("Enter deposit: "); int deposit = stdin.nextInt()); savings.addFunds(deposit); System.out.print("Enter withdrawal: "); int withdrawal = stdin.nextInt()); savings.removeFunds(withdrawl); System.out.println("Closing balance: " + savings.getBalance()); }

Class BankAccount Instance variable balance Construct a new empty bank account BankAccount() Construct a new bank account with initial funds BankAccount(int n) throws NegativeAmountException Deposit funds addFunds(int n) throws NegativeAmountException Withdraw funds removeFunds(int n) throws NegativeAmountException Get balance Int getBalance()

Class BankAccount // BankAccount(): default constructor for empty balance public BankAccount() { balance = 0; } // BankAccount(): specific constructor for a new balance n public BankAccount(int n) throws NegativeAmountException { if (n >= 0) { balance = n; } else { throw new NegativeAmountException("Bad balance"); }

Class BankAccount // getBalance(): return the current balance public int getBalance() { return balance; } // addFunds(): deposit amount n public void addFunds(int n) throws NegativeAmountException { if (n >= 0) { balance += n; } else { throw new NegativeAmountException("Bad deposit"); }

Class BankAccount // removeFunds(): withdraw amount n public void removeFunds(int n) throws NegativeAmountException { if (n < 0) { throw new NegativeAmountException("Bad withdrawal"); } else if (balance < n) { throw new NegativeAmountException("Bad balance"); } else { balance -= n; }

Using NegativeAmountException System.out.print("Enter deposit: "); try { int deposit = stdin.nextInt(); savings.addFunds(deposit); } catch (NegativeAmountException e) { System.err.println(“Cannot deposit negative funds“); System.exit(0); }

Using NegativeAmountException System.out.print("Enter withdrawal: "); try { int withdrawal = stdin.nextInt(); savings.removeFunds(withdrawl); } catch (NegativeAmountException e) { if (e.message().equals("Bad withdrawal")) System.err.println(“Cannot withdraw negative funds“); else { System.err.println("Withdrawal cannot leave " "negative balance"); } System.exit(0); }