Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.

Slides:



Advertisements
Similar presentations
Topics Introduction Types of Errors Exceptions Exception Handling
Advertisements

Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Yoshi
Exception Handling. Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code.
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.
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.
Index Exception handling Exception In Java Exception Types
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
Java Programming Exceptions. Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
Exceptions and Exception Handling (2) Carl Alphonce CSE116.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
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:
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.
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.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
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
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 1. Introduction Users may use our programs in an unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected.
Object Oriented Programming
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
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.
Slides Credit Umair Javed LUMS Web Application Development.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
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.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
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:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
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.
Chapter 10 – Exception Handling
Topic: Exception Handling
Introduction to Exceptions in Java
Introduction Exception handling Exception Handles errors
Chapter 12 Exception Handling and Text IO Part 1
Java Basics Exception Handling.
Presentation transcript:

Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between errors and exceptions To show the use and syntax of exceptions To describe how to create your own exception classes.

Traditional Methods of Handling Errors In most procedural languages, the standard way of indicating an error condition is by returning an error code. The calling code typically did one of the following: Testing the error code and taking the appropriate action. Ignoring the error code. It was considered good programming practice to only have one entry point and one exit point from any given function. This often lead to very convoluted code. If an error occurred early in a function, the error condition would have to be carried through the entire function to be returned at the end. This usually involved a lot of if statements and usually lead to gratituitously complex code.

Error handling through Exceptions Gradually, programmers began to realize that the traditional method of handling errors was too cumbersome for most error handling situations. This gave rise to the Exception concept When an error occurs, that represents and Exceptional condition Exceptions cause the current program flow to be interrupted and transferred to a registered exception handling block. This might involve unrolling the method calling stack. Exception handling involves a well-structured goto

Exception -Terminology When an error is detected, an exception is thrown Any exception which is thrown, must be caught by and exception handler If the programmer hasn't provided one, the exception will be caught by a catch-all exception handler provided by the system. The default exception handler may terminate the application. Exceptions can be rethrown if the exception cannot be handled by the block which caught the exception Java has 5 keywords for exception handling: try catch finally throw throws

Exception -Class Hierarchy The following is the class hierarchy for Java exceptions: Throwable + Throwable(String message) + getMessage(): String + printStackTrace():void ErrorException Errors: An error represents a condition serious enough that most reasonable applications should not try to catch. - Virtual Machine Error - out of memory - stack overflow - Thread Death - Linkage Error Exceptions: An error which reasonable applications should catch - Array index out of bounds - Arithmetic errors (divide by zero) - Null Pointer Exception - I/O Exceptions See the Java API Specification for more.

Exceptions -Checked and Unchecked Java allows for two types of exceptions: Checked. If your code invokes a method which is defined to throw checked exception, your code MUST provide a catch handler The compiler generates an error if the appropriate catch handler is not present Unchecked These exceptions can occur through normal operation of the virtual machine. You can choose to catch them or not. If an unchecked exception is not caught, it will go to the default catch- all handler for the application All Unchecked exceptions are subclassed from RuntimeException

Exceptions -Syntax try { // Code which might throw an exception //... } catch(FileNotFoundException x) { // code to handle a FileNotFound exception } catch(IOException x) { // code to handle any other I/O exceptions } catch(Exception x) { // Code to catch any other type of exception } finally { // This code is ALWAYS executed whether an exception was thrown // or not. A good place to put clean-up code. ie. close // any open files, etc... }

Exceptions -Defining checked exceptions Any code which throws a checked exception MUST be placed within a try block. Checked exceptions are defined using the throws keyword in the method definition: public class PrintReader extends Reader { public int read() throws IOException [...] public void method1() { PrintReader aReader; [... initialize reader...] try { int theCharacter = aReader.read(); } catch(IOException x) { [...]

Exceptions -throwing multiple exceptions A Method can throw multiple exceptions. Multiple exceptions are separated by commas after the throws keyword: public class MyClass { public int computeFileSize() throws IOException, ArithmeticException [...] public void method1() { MyClass anObject = new MyClass(); try { int theSize = anObject.computeFileSize(); } catch(ArithmeticException x) { //... } catch(IOException x) { //...

Exceptions -catching multiple exceptions Each try block can catch multiple exceptions. Start with the most specific exceptions FileNotFoundException is a subclass of IO Exception It MUST appear before IOException in the catch list public void method1() { FileInputStream aFile; try { aFile = new FileInputStream(...); int aChar = aFile.read(); //... } catch(FileNotFoundException x) { //... } catch(IOException x) { //...

Exception -The catch-all Handler Since all Exception classes are a subclass of the Exception class, a catch handler which catches "Exception" will catch all exceptions. It must be the last in the catch List public void method1() { FileInputStream aFile; try { aFile = new FileInputStream(...); int aChar = aFile.read(); //... } catch(IOException x) { //... } catch(Exception x) { // Catch All Exceptions

The finally block public void method1() { FileInputStream aFile; try { aFile = new FileInputStream(...); int aChar = aFile.read(); //... } catch(IOException x) { //... } catch(Exception x) { // Catch All other Exceptions } finally { try { aFile.close(); } catch (IOException x) { // close might throw an exception }

Throwing Exceptions You can throw exceptions from your own methods To throw an exception, create an instance of the exception class and "throw" it. If you throw checked exceptions, you must indicate which exceptions your method throws by using the throws keyword public void withdraw(float anAmount) throws InsufficientFundsException { if (anAmount<0.0) throw new IllegalArgumentException("Cannot withdraw negative amt"); if (anAmount>balance) throw new InsuffientFundsException("Not enough cash"); balance = balance - anAmount; }

Re-throwing Exceptions If you catch an exception but the code determines it cannot reasonably handle the exception, it can be rethrown: public void addURL(String urlText) throws MalformedURLException { try { URL aURL = new URL(urlText); //... } catch(MalformedURLException x) { // determine that the exception cannot be handled here throw x; }

Automatically Passing Exceptions If your method is defined to throw an exception, you need not catch it within your method public void addURL(String urlText) throws MalformedURLException { URL aURL = new URL(urlText); // if the above throws a MalformedURLException, we need not have // a try/catch block here because the method is defined to // throw that exception. Any method calling this method MUST // have a try/catch block which catches MalformedURLExceptions. // Control is automatically transferred to that catch block. }

Defining Your Own Exceptions To define your own exception you must do the following: Create an exception class to hold the exception data. Your exception class must subclass "Exception" or another exception class Note: to create unchecked exceptions, subclass the RuntimeException class. Minimally, your exception class should provide a constructor which takes the exception description as its argument. To throw your own exceptions: If your exception is checked, any method which is going to throw the exception must define it using the throws keyword When an exceptional condition occurs, create a new instance of the exception and throw it.