Chapter 12 Exception Handling and Text IO Part 1

Slides:



Advertisements
Similar presentations
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Advertisements

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 13 Exception.
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.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
1 Exception Handling (in a nutshell). 2 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
CS203 Java Object Oriented Programming Errors and Exception Handling.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 14 Exception Handling and Text.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 12 Exception Handling and Text.
1 Chapter 18 Exception Handling. 2 Motivations F Program runs into a runtime error –program terminates abnormally F How can you handle the runtime error.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Exception Handling.
COMP Exception Handling Yi Hong June 10, 2015.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 15 Exceptions and.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Exception Handling and Text.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exceptions and Assertions Chapter 15 – CSCI 1302.
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.
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:
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 15 Exceptions and Assertions Nothing is impossible.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
CS 112 Programming 2 Lecture 08 Exception Handling & Text I/O (1)
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Chapter 12 Exceptions and File Input/Output
Chapter 13 Exception Handling
Chapter 10 – Exception Handling
Chapter 12 Exception Handling And Text IO
Chapter 13 Exception Handling
Exception Handling in Java Reference: COS240 Syllabus
Topic: Exception Handling
Introduction to Exceptions in Java
Chapter 12 Exception Handling and Text IO
Chapter 12 Exception Handling & Text Files
Chapter 7 Exceptions and Assertions
Chapter 12 Exception Handling and Text IO
Chapter 14 Exception Handling and Text IO
Chapter 12 Exception Handling
Chapter 11 Exception Handling and Text I/O
Chapter 12 Exception Handling and Text IO
Chapter 12 Exception Handling and Text IO
Web Design & Development Lecture 7
Chapter 12 Exception Handling and Text IO
Chapter 14 Exception Handling and Text IO
Chapter 13 Exception Handling
Lecture 11 Objectives Learn what an exception is.
Chapter 12 Exception Handling and Text IO
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Tutorial Exceptions Handling.
Chapter 14 Exception Handling and Text IO
Chapter 12 Exception Handling and Text IO
Tutorial MutliThreading.
Chapter 12 Exception Handling and Text IO
Java Basics Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Chapter 12 Exception Handling and Text IO Part 1

Exception Handling Exception handling enables a program to deal with exceptional situations and continue its normal execution No exception handling Quotient Run With if-else QuotientWithIf Run With a method QuotientWithMethod Run With try-catch QuotientWithException Run The benefit of using try-catch is that it enables a method to throw an exception to its caller method. Without this capability, a method must handle the exception itself or terminate the program

Arithmetic Exception import java.util.Scanner; public class QuotientWithException { public static int quotient(int number1, int number2) { if (number2 == 0) throw new ArithmeticException("Divisor cannot be zero"); return number1 / number2; } public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter two integers System.out.print("Enter two integers: "); int number1 = input.nextInt(); int number2 = input.nextInt(); try { int result = quotient(number1, number2); System.out.println(number1 + " / " + number2 + " is " + result); catch (ArithmeticException ex) { System.out.println("Exception: an integer " + "cannot be divided by zero "); System.out.println("Execution continues ...");

Exceptions are objects based on the superclass java.lang.Throwable Exception Types Exceptions are objects based on the superclass java.lang.Throwable

Exceptions are objects based on the superclass java.lang.Throwable Exception Types Exceptions are objects based on the superclass java.lang.Throwable

Exception Types Exceptions are objects based on the superclass java.lang.Throwable Built-in exceptions Description Arithmetic Exception Condition has occurred in an arithmetic operation. ArrayIndexOutOfBoundException Array has been accessed with an illegal index, either negative or greater than or equal to the size of the array. ClassNotFoundException Access a class whose definition is not found FileNotFoundException A file is not accessible or does not open. IOException An input-output operation failed or interrupted NullPointerException Referring to the members of a null object. Null represents nothing NumberFormatException A method could not convert a string into a numeric format. StringIndexOutOfBoundsException String class methods to indicate that an index is either negative than the size of the string

NullPointer Exception FileNotFound Exception Exception Examples NullPointer Exception FileNotFound Exception //Java program to demonstrate NullPointerException class NullPointer_Demo {     public static void main(String args[])     {         try {             String a = null; //null value             System.out.println(a.charAt(0));         } catch(NullPointerException e) {             System.out.println("NullPointerException..");         }     } } //Java program to demonstrate FileNotFoundException import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader;  class File_notFound_Demo {        public static void main(String args[])  {             // Following file does not exist             File file = new File("E://file.txt");             FileReader fr = new FileReader(file);         } catch (FileNotFoundException e) {            System.out.println("File does not exist"); Output: NullPointerException.. File does not exist

InputMismatchException Another way to handle similar exceptions is with the help of the InputMismatchException class Example: When executing input.nextInt(), an InputMismatchException occurs if the input entered is not an int and the control is transferred to the catch block The statements in the catch block are now executed InputMismatchExceptionDemo Run

Checked & Unchecked Exceptions Throwable Exception Error All other exceptions RuntimeException subclasses subclasses subclasses Checked Exceptions Unchecked Exceptions

Program does not compile if any of these are present Errors caused by your program and external circumstances These rare internal system errors are thrown by JVM. If one occurs, notify the user and terminate the program Throwable Exception Error Caused by coding faults like bad casting, out-of-bounds array, etc. All other exceptions RuntimeException subclasses subclasses subclasses Checked Exceptions Unchecked Exceptions Program does not compile if any of these are present They happen only after the programs starts running

Handling Unchecked Exceptions In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example: A NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it An IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array These logic errors should be corrected in the program Unchecked exceptions can occur anywhere in the program To avoid cumbersome overuse of try-catch, Java does not mandate you to write code to catch unchecked exceptions

Declaring, Throwing and Catching Java’s exception-handling model is based on three operations: Declaring an exception Throwing an exception Catching an exception Exceptions are declared in and thrown from a method. The caller of that method can catch and handle the exception

Declaring Exceptions Examples: Every method must state the types of checked exceptions it might throw This is known as declaring exceptions Examples: public void myMethod() throws IOException public void myMethod() throws IOException, OtherException

Throwing Exceptions When the program detects an error, the program can create an instance of an appropriate exception type and throw it This is known as throwing an exception Examples: throw new TheException(); TheException ex = new TheException(); throw ex;

Example: Throwing Exception /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }

Catching Exceptions When an exception is thrown, it can be caught and handled in a try-catch block. If no exceptions arise during the execution of the try block, the catch blocks are skipped try { statements; // Statements that may throw exceptions } catch (Exception1 exVar1) { // handler for exception1 catch (Exception2 exVar2) { // handler for exception2 ... catch (ExceptionN exVarN) { // handler for exceptionN If an exception is not caught in the current method, it is passed to the calling method. The process is repeated until the exception is caught or passed to main()

Example: Catching Exceptions If the exception type is Exception3, it is caught by the catch block for ex3 in method2. statement5 is skipped, and statement6 is executed If the exception type is Exception2, method2 is aborted, control is returned to method1, and the exception is caught by the catch block for ex2 in method1. statement3 is skipped. statement4 is executed If the exception type is Exception1, method1 is aborted, control is returned to main, and the exception is caught by the catch block for ex1 in main. statement1 is skipped. statement2 is executed If the exception type is not caught in method2, method1, or main, the program terminates, and statement1 and statement2 are not executed

Catch or Declare Checked Exceptions Java forces you to deal with checked exceptions. If a method declares a checked exception, you must invoke it in a try-catch block or declare to throw the exception in the calling method Example: void p2() throws IOException { if (file closed) throw new IOException("File is closed");} If p1() invokes p2() then we must write code as shown in (a) or (b)  

Example: Declaring/Throwing/Catching Checked Exception This example demonstrates declaring, throwing, and catching exceptions by modifying the setRadius() in the Circle class defined in Chapter 9 The new setRadius() throws an exception if radius is negative CircleWithException TestCircleWithException Run

Rethrowing Exceptions An exception handler can rethrow the exception if the handler can’t process the exception or simply wants to let its caller be notified of the exception try { // statements } catch(TheException ex) { // perform some operations throw ex; The catch block first catches and processes the exception, and then rethrows it to the caller so that other handlers in the caller get a chance to process ex

The finally Block The code in the finally block is executed under all circumstances, regardless of whether an exception occurs in the try block or whether an exception is caught if it occurs try { statements; } catch(TheException ex) { handling ex; finally { finalStatements;

Trace a Program Execution animation Trace a Program Execution Suppose no exceptions in the statements try { statements; } catch(TheException ex) { handling ex; finally { finalStatements; Next statement;

Trace a Program Execution animation Trace a Program Execution The final block is always executed try { statements; } catch(TheException ex) { handling ex; finally { finalStatements; Next statement;

Trace a Program Execution animation Trace a Program Execution Next statement in the method is executed try { statements; } catch(TheException ex) { handling ex; finally { finalStatements; Next statement;

Trace a Program Execution animation Trace a Program Execution Suppose an exception of type Exception1 is thrown in statement2 try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; finally { finalStatements; Next statement;

Trace a Program Execution animation Trace a Program Execution The exception is handled. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; finally { finalStatements; Next statement;

Trace a Program Execution animation Trace a Program Execution The final block is always executed. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; finally { finalStatements; Next statement;

Trace a Program Execution animation Trace a Program Execution The next statement in the method is now executed. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; finally { finalStatements; Next statement;

Trace a Program Execution animation Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; catch(Exception2 ex) { throw ex; finally { finalStatements; Next statement; statement2 throws an exception of type Exception2.

Trace a Program Execution animation Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; catch(Exception2 ex) { throw ex; finally { finalStatements; Next statement; Handling exception

Trace a Program Execution animation Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; catch(Exception2 ex) { throw ex; finally { finalStatements; Next statement; Execute the final block

Trace a Program Execution animation Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; catch(Exception2 ex) { throw ex; finally { finalStatements; Next statement; Rethrow the exception and control is transferred to the caller