Exceptions and Exception Handling (2) Carl Alphonce CSE116.

Slides:



Advertisements
Similar presentations
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Advertisements

Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
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.
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
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.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
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.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
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.
Exceptions and Exception Handling Carl Alphonce CSE116.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
Exceptions and Exception Handling (1) Carl Alphonce CSE116.
Exceptions and Exception Handling (continued) Carl Alphonce CSE116.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
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. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
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
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
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.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
CIS 270—Application Development II Chapter 13—Exception Handling.
Slides Credit Umair Javed LUMS Web Application Development.
Exceptions1 Syntax, semantics, and pragmatics. Exception create If (some error){ throw new SomeException(”some message”); } Exceptions2.
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects CS 146 Class Notes Fall 10.
Exception. Runtime Error Consider the following program: public class BadArray { public static void main(String[] args) { // Create an array with three.
VB.Net - Exceptions Copyright © Martin Schray
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
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.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
© 2004 Pearson Addison-Wesley. All rights reserved April 24, 2006 Exceptions (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING 2006.
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.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
C# Exceptions 1 CNS 3260 C#.NET Software Development.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Introduction to Exceptions in Java CS201, SW Development Methods.
Geoff Holmes Week 5 problems Handling Throwing Catching Multiple exceptions Finally clause Examples Exception Handling.
Exceptions in the Java programming language J. W. Rider.
Java Exceptions a quick review….
Introduction to Exceptions in Java
Introduction to Exceptions in Java
CSE 501N Fall ’09 17: Exception Handling
Exception Handling Chapter 9.
Chapter 11—Exceptions Handling Exceptions Throwing Exceptions.
ATS Application Programming: Java Programming
Exception Handling and Reading / Writing Files
Exception Handling Chapter 9 Edited by JJ.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Presentation transcript:

Exceptions and Exception Handling (2) Carl Alphonce CSE116

Intermediate Java How are exceptions generated?  An exception is an object.  An exception must derive from the java.lang.Exception class.  An exception object must be instantiated from an exception class. new IndexOutOfBoundsException()  An exception must be thrown: throw new IndexOutOfBoundsException()

Intermediate Java What happens when an exception is thrown?  The exception is thrown until one of two things happens: an exception handler for the thrown exception is found, or the exception is uncaught (which typically results in program termination).  More technically, the runtime stack is unwound until a handler is found or the stack is empty.

Intermediate Java Runtime stack?  Every time a method is called, an invocation record is pushed onto the runtime stack.  An invocation record stores things like: parameter values local variables return value return location  When a method finishes, its corresponding invocation record is removed (“popped”) from the runtime stack.

Intermediate Java Exceptions and flow-of-control  When an exception is thrown, the regular flow of control is interrupted.  Invocation records are popped from runtime stack until an exception handler is found.  Because of this, code in a method after a “throw” is not executed if the throw occurs.

Intermediate Java Example public int someMethod() { stmt1; stmt2; if (x<=0) { throw new Exception(); } stmt3; return x; }

Intermediate Java Example (if x > 0) public int someMethod() { stmt1; stmt2; if (x<=0) { throw new Exception(); } stmt3; return x; }

Intermediate Java Example (if x <= 0) public int someMethod() { stmt1; stmt2; if (x<=0) { throw new Exception(); } stmt3; return x; }

Intermediate Java Catching an exception  If you want to catch an exception, you must indicate: from which segment of code you are prepared to handle an exception which exception(s) you are going to handle  You can also: include a “cleanup” case to release resources acquired, regardless of whether an exception was thrown

Intermediate Java The try block  To indicate the segment of code from which you are prepared to handle an exception, place it in a try block: stmt1; try { stmt2; stmt3; } stmt4;

Intermediate Java A catch block  A catch block is an exception handler for a specific type of exception: try { // code that may throw exception } catch (Exception e) { // code to handle exception }

Intermediate Java Multiple catch blocks  Can place many catch blocks (exception handlers) after a try block: try { // code that may throw exception } catch (IndexOutOfBoundsException e) { // code to handle an index out of bounds exception } catch (MalformedURLException e) { // code to handle a malformed URL exception } catch (Exception e) { // code to handle a general exception }

Intermediate Java Recall there is an exception hierarchy:  Here’s part of the hierarchy: Exception  IOException  FileNotFoundException  MalformedURLException  RuntimeException  IndexOutOfBoundsException  NullPointerException

Intermediate Java Catch block ordering: specific to general  Catch blocks are tried in the order they are written: try { // code that may throw exception } catch (IndexOutOfBoundsException e) { // code to handle index out of bounds exception } catch (RuntimeException e) { // code to handle runtime exception } catch (Exception e) { // code to handle any other exception }

Intermediate Java Now consider a slightly different part of the hierarchy:  Here’s part of the hierarchy: Exception  IOException  FileNotFoundException  MalformedURLException  RuntimeException  IndexOutOfBoundsException  NullPointerException

Intermediate Java Catch block ordering: general to specific?  Catch blocks are tried in the order they are written: try { // code that may throw exception } catch (Exception e) { // code to handle any exception } catch (RuntimeException e) { // code to handle a runtime exception // this is never reached! } catch (IndexOutOfBoundsException e) { // code to handle index out of bounds exception // this is never reached! }

Intermediate Java Finally clause  Optional  Used to release resources back to OS Shared resources are often acquired inside a try block (e.g. a file is opened for writing) These resources must be released (e.g. the file must be closed so some other piece of code can use it):  if an exception is NOT thrown in the try block  if an exception IS thrown in the try block

Intermediate Java Flow of control: no exception is thrown // some code try { // code that may throw exception } catch (IndexOutOfBoundsException e) { // code to handle index out of bounds exception } catch (RuntimeException e) { // code to handle runtime exception } catch (MalformedURLException e) { // code to handle malformed URL exception } finally { // cleanup code } // more code

Intermediate Java Flow of control: handled exception (e.g. RuntimeException) is thrown // some code try { // code that throws a RuntimeException } catch (IndexOutOfBoundsException e) { // code to handle index out of bounds exception } catch (RuntimeException e) { // code to handle runtime exception } catch (MalformedURLException e) { // code to handle malformed URL exception } finally { // cleanup code } // more code

Intermediate Java Flow of control: unhandled exception (e.g. FileNotFoundException) is thrown // some code try { // code that throws a RuntimeException } catch (IndexOutOfBoundsException e) { // code to handle index out of bounds exception } catch (RuntimeException e) { // code to handle runtime exception } catch (MalformedURLException e) { // code to handle malformed URL exception } finally { // cleanup code } // more code

Intermediate Java Defining your own exception classes  Since exceptions are just objects derived from the type java.util.Exception, you can define your own.  There are *many* predefined exceptions – one will likely meet your needs.  To define your own:

Intermediate Java An example of an exception class public class IllegalStateException extends RuntimeException { public IllegalStateException() { super(); } public IllegalStateException(String s) { super(s); } public IllegalStateException(String message, Throwable cause) { super(message, cause); } public IllegalStateException(Throwable cause) { super(cause); }

Intermediate Java Defining your own exceptions  You generally only provide an appropriate set of constructors.  Rest of functionality is inherited.