13 Copyright © 2011, Oracle and/or its affiliates. All rights reserved. Handling Errors.

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

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.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
Index Exception handling Exception In Java Exception Types
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
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.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
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.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
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.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
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.
Java Software Solutions Foundations of Program Design Sixth Edition
Preventing and Correcting Errors
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Object Oriented Programming
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Program Errors Syntax errors Logic errors
CIS 270—Application Development II Chapter 13—Exception Handling.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Object Oriented Programming with Java (150704).  Throwable Exception (This class will catch exceptions generated by prog.) (Create your own custom exception.
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
Practice Session 9 Exchanger CyclicBarrier Exceptions.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
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.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Recitation 3 2D Arrays, Exceptions. 2D arrays 2D Arrays Many applications have multidimensional structures: ●Matrix operations ●Collection of lists ●Board.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
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:
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.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Object Throwable ErrorException RuntimeException.
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
Advanced Programming Behnam Hatami Fall 2017.
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.
ATS Application Programming: Java Programming
Exception Handling and Reading / Writing Files
Lecture 9: Exceptions in Java CS201j: Engineering Software
Web Design & Development Lecture 7
Java Exceptions Dan Fleck CS211.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Java Basics Exception Handling.
Presentation transcript:

13 Copyright © 2011, Oracle and/or its affiliates. All rights reserved. Handling Errors

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Objectives After completing this lesson, you should be able to: Describe the different kinds of errors that can occur and how they are handled in Java Describe what exceptions are used for in Java Determine what exceptions are thrown, for any foundation class Write code to handle an exception thrown by the method of a foundation class

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Topics Handling errors: an overview Propagation of exceptions Catching and throwing exceptions Multiple exceptions and errors

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Reporting Exceptions Coding mistake: int[] intArray = new int[5]; intArray[5] = 27; Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at TestErrors.main(TestErrors.java:17) Output in console:

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Reporting Exceptions Calling code in main() : TestArray myTestArray = new TestArray(5); myTestArray.addElement(5, 23); public class TestArray { int[] intArray; public TestArray (int size) { intArray = new int[size]; } public void addElement(int index, int value) { intArray[index] = value; } TestArray class:

Copyright © 2011, Oracle and/or its affiliates. All rights reserved How Exceptions Are Thrown Normal program execution: 1.Caller method calls worker method. 2.Worker method does work. 3.Worker method completes work, and then execution returns to caller method. When an exception occurs, this sequence changes: Exception is thrown and either: –A special Exception object is passed to a special method-like catch block in the current method or –Execution returns to the caller method

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Types of Exceptions Three main types of Throwable: Error –Typically unrecoverable external error –Unchecked RuntimeException –Typically programming mistake –Unchecked Exception –Recoverable error –Checked (must be caught or thrown)

Copyright © 2011, Oracle and/or its affiliates. All rights reserved OutOfMemoryError Programming mistake: ArrayList theList = new ArrayList(); while(true) { String theString = "A test String"; theList.add(theString); if (theList.size()% == 0) { System.out.println("List now has " + theList.size()/ " million elements!"); } List now has 240 million elements! List now has 250 million elements! Exception in thread "main" java.lang.OutOfMemoryError: Java heap space Output in console:

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Topics Handling errors: an overview Propagation of exceptions Catching and throwing exceptions Multiple exceptions and errors

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Method Stack main() doThis() doThat() The main() method calls doThis() on a Utils object. class Test class Utils The doThis() method calls the doThat() method on the same object. doThat() returns and execution continues in doThis(). doThis() returns and execution continues in main(). main() completes execution and exits.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Call Stack: Example Test class: Utils class: public void doThis() { doThat(); return; public void doThat() throws Exception{ if (some_problem) throw new Exception(); return; public static void main (String args[]) { Utils theUtils = new Utils(); theUtils.doThis(); }

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Throwing Throwables main() doThis() doThat() class Test class Utils Exception thrown in doThat() doThis() must catch OR throw the exception. Execution returns to doThis(), but not via the normal return mechanism.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Throwing Throwables main() doThis() doThat() class Test class Utils Exception thrown in doThat() If doThis() throws the exception (does NOT catch it), then … … main() must catch it OR throw it.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Working with Exceptions in NetBeans Throwing an exception within the method requires further steps. NetBeans uses a tooltip to give you your two options. No exceptions thrown; nothing needs be done to deal with them.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Catching an Exception Now exception needs to be dealt with in doThis(). The try/catch block catches exception and handles it. doThat() now throws an exception.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Uncaught Exception main() doThis() doThat() class Test class Utils Exception thrown in doThat() Thrown again in doThis() Thrown again in main() StackTrace printed to the console

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Exception Printed to Console Example of main() throwing exception main() is now set up to throw exception. Because main() throws the exception, it now prints call stack to console.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Summary of Exception Types A Throwable is a special type of Java object: Only object type that is used as the argument in a catch clause Only object type that can be “thrown” to the calling method Has two subclasses: –Error — Automatically thrown to the calling method if created –Exception — Must be explicitly thrown to the calling method OR — Caught using a try/catch block — Has a subclass RuntimeException that is automatically thrown to the calling method

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Quiz Which one of the following statements is true? a.A RuntimeException must be caught. b.A RuntimeException must be thrown. c.A RuntimeException must be caught or thrown. d.A RuntimeException is thrown automatically.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Quiz Which of the following objects are checked exceptions? a.All objects of type Throwable b.All objects of type Exception c.All objects of type Exception that are not of type RuntimeException d.All objects of type Error e.All objects of type RuntimeException

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Topics Handling errors: an overview Propagation of exceptions Catching and throwing exceptions Multiple exceptions and errors

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Exceptions in the Java API Documentation Click to get the detail of createNewFile(). Note exceptions that can be thrown.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Calling a Method That Throws an Exception createNewFile() can throw a checked exception, so it must throw or catch. Constructor causes no compilation problems.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Working with a Checked Exception Catching IOException: public static void main(String args[]) { try { testCheckedException(); } catch (IOException e) { System.out.println(e); } public static void testCheckedException() throws IOException{ File testFile = new File("//testFile.txt"); testFile.createNewFile(); System.out.println("File exists: " + testFile.exists()); }

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Best Practices Catch the actual exception thrown, not the exception or Throwable superclass. Examine the exception to find out the exact problem so you can recover cleanly. You do not need to catch every exception. –A programming mistake should not be handled. It must be fixed. –Ask yourself, "Does this exception represent behavior I want the program to recover from?"

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Bad Practices public static void main (String args[]) { try { createFile("c:/testFile.txt"); } catch (Exception e) { System.out.println("Problem creating the file!"); } public static void createFile(String fileName) throws IOException { File f = new File(fileName); f.createNewFile(); int[] intArray = new int[5]; intArray[5] = 27; } Catching superclass? No processing of the Exception object?

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Bad Practices public static void main (String args[]) { try { createFile("c:/testFile.txt"); } catch (Exception e) { System.out.println(e); } public static void createFile(String fileName) throws IOException { File f = new File(fileName); System.out.println(fileName + " exists? " + f.exists()); f.createNewFile(); System.out.println(fileName + " exists? " + f.exists()); int[] intArray = new int[5]; intArray[5] = 27; } What is the object type? toString() is called on this object.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Topics Handling errors: an overview Propagation of exceptions Catching and throwing exceptions Multiple exceptions and errors

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Multiple Exceptions public static void createFile() throws IOException { File testF = new File("c:/notWriteableDir"); File tempF = testFile.createTempFile("te", null, testF); System.out.println("Temp filename: " + tempFile.getPath()); int myInt[] = new int[5]; myInt[5] = 25; } Directory must be writeable (IOException). Array index must be valid (ArrayIndexOutOfBounds). Argument must be three or more characters (IllegalArgumentException).

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Catching IOException public static void main (String args[]) { try { createFile(); } catch (IOException ioe) { System.out.println(ioe); } public static void createFile() throws IOException { File testF = new File("c:/notWriteableDir"); File tempF = testFile.createTempFile("te", null, testF); System.out.println("Temp filename is " + tempFile.getPath()); int myInt[] = new int[5]; myInt[5] = 25; }

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Catching IllegalArgumentException public static void main (String args[]) { try { createFile(); } catch (IOException ioe) { System.out.println(ioe); } catch (IllegalArgumentException iae) { System.out.println(iae); } public static void createFile() throws IOException { File testF = new File("c:/writeableDir"); File tempF = testFile.createTempFile("te", null, testF); System.out.println("Temp filename is " + tempFile.getPath()); int myInt[] = new int[5]; myInt[5] = 25; }

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Catching Remaining Exceptions public static void main (String args[]) { try { createFile(); } catch (IOException ioe) { System.out.println(ioe); } catch (IllegalArgumentException iae) { System.out.println(iae); } catch (Exception e) { System.out.println(e); } public static void createFile() throws IOException { File testF = new File("c:/writeableDir"); File tempF = testFile.createTempFile("te", null, testF); System.out.println("Temp filename is " + tempFile.getPath()); int myInt[] = new int[5]; myInt[5] = 25; }

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Summary In this lesson, you should have learned how to: Describe the different kinds of errors that can occur and how they are handled in Java Describe what exceptions are used for in Java Determine what exceptions are thrown, for any foundation class Write code to handle an exception thrown by the method of a foundation class

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Practice 13-1 Overview: Using a Try/Catch Block to Handle an Exception In this practice, you handle an exception thrown by the parse() method of SimpleDateFormat. During the practice, you: Use the Java API documentation to examine the SimpleDateFormat class and find the exception thrown by its parse() method Create a class that calls the parse() method Write a try/catch block to catch the exception thrown by parse()

Copyright © 2011, Oracle and/or its affiliates. All rights reserved Practice 13-2 Overview: Catching and Throwing a Custom Exception In this practice, you use a custom exception named InvalidSkillException. You use this with the Employee Tracking application that you designed and built in Practices 12-1 and 12-2.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved