For use of Cleveland State's IST410 Students only 1 Exception.

Slides:



Advertisements
Similar presentations
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

Yoshi
Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
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.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Java Exceptions. Exceptions Often in computing, operations cannot properly execute because some sort of error has occurred. Some examples: Often in computing,
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
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.
COMP201 Java Programming Topic 6: Exceptions Reading: Chapter 11.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
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.
11-Jun-15 Exceptions. 2 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.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class 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 CIS 304 Intermediate Java Programming for Business.
交通大學資訊工程學系 Programming in Java Exception Handling 蔡文能 交通大學資訊工程學系
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.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
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.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
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.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Exception. Runtime Error Consider the following program: public class BadArray { public static void main(String[] args) { // Create an array with three.
COMP Exception Handling Yi Hong June 10, 2015.
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in.
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.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
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.
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.
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.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Introduction to Exceptions in Java CS201, SW Development Methods.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
CS102 – Exceptions David Davenport Latest: May 2015
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
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
Web Design & Development Lecture 7
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Chapter 12 Exception Handling and Text IO Part 1
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.
Exceptions 10-May-19.
Java Basics Exception Handling.
Presentation transcript:

For use of Cleveland State's IST410 Students only 1 Exception

For use of Cleveland State's IST410 Students only 2 Exceptions Handling l Exceptions are error conditions from which a program can recover from l Examples of exception include m Using an Array index greater than the array size m Trying to use an object reference that refers nowhere m Trying to open a file that does not exist l Decisions to be made in a program include m Should the error condition be trapped m Recovery action to be taken in case of error l Untrapped error conditions leads to program failure

For use of Cleveland State's IST410 Students only 3 Exception handling construct try { // code that may cause exception } catch (ExceptionType1 et1) { // code to handle ExceptionType1 } catch (ExceptionType2 et2) { // code to handle ExceptionType2 } finally { // code }

For use of Cleveland State's IST410 Students only 4 Partial Exception Hierarchy Throwable ErrorException AWTError VirtualMachineError RuntimeException IOException NullPointerExceptionArithmeticException EOFException

For use of Cleveland State's IST410 Students only 5 Exception Hierarchy l All exceptions are derived from Throwable l Only objects that are instances of Throwable are thrown by JVM, or can be thrown by throw statement l Throwable has 2 known subclasses: Error, Exception l Error indicates serious problems that an application normally does not try to recover from l Direct Subclasses of Error: m AWTError, LinkageError, ThreadDeath, VirtualMachineError l Exception indicates problems that an application might catch

For use of Cleveland State's IST410 Students only 6 RuntimExceptions class l Some of the direct subclasses of Exception are: RuntimeException, and IOException (and others) l RuntimeException happens mostly due to programming error l Examples m ArithmeticException - ex. wrong arithmetic expression m IndexOutOfBoundsException - exceed the array boundaries m NumberFormatException - bad convert from String to number l Should a program try to recover from these errors?

For use of Cleveland State's IST410 Students only 7 Other Exceptions l Exceptions that do not fall into RuntimeException category indicate error conditions that are not necessarily due to coding errors l These exceptions are also known as checked exception l Compiler enforces declaration of checked exception l Examples m FileNotFoundException - file not found m ObjectStreamException - Error in Object Streams l A program may attempt to deal with such exceptions

For use of Cleveland State's IST410 Students only 8 Code that may cause Exceptions try { // code or Methods that may cause exception } l Code that may cause exception(s) are put in a try block l Checked exceptions that are not handled in a method, but thrown, must be declared using a throws clause public int getNumber(String s) throws NullPointerException { // method code goes here }

For use of Cleveland State's IST410 Students only 9 throws l A method may ‘throws’ more than one exception public int getNumber(String s) throws NullPointerException, NumberTooBigException { // method code goes here } l Unchecked exceptions may also be thrown by a method

For use of Cleveland State's IST410 Students only 10 Throwing an Exception l Example of throws usage public int getNumber(String s) throws NullPointerException, NumberTooBigException { if (s == null) throw new NullPointerException(); int i = Integer.parseInt(s); if ( i > 200) throw new NumberTooBigException(); return i; } l When an exception is thrown in a method, it is an implicit return unless the there is a local catch or finally block

For use of Cleveland State's IST410 Students only 11 Throwing an Exception l We can create exception objects and throw them public int getNumber(String s) throws NullPointerException, NumberTooBigException { if (s == null) { NullPointerException np = new NullPointerException(); throw np; } // rest of the method code }

For use of Cleveland State's IST410 Students only 12 Catching an Exception l As you can see, exception is a type of object l A method creates an exception object that someone must catch try { int i = getNumber(“234”) } catch (NullPointerException np) { System.out.println(“The String is empty”); } l A method may catch its own exception or throw the exception to its caller

For use of Cleveland State's IST410 Students only 13 Catching an Exception l A method may catch more than one exception types try { int i = getNumber(“234”) } catch (NullPointerException np) { System.out.println(“The String is empty”); } catch (NumberTooBigException ntb) { System.out.println(“Number greater than 200”); } catch (Exception e) { System.out.println(“Unforeseen Error”); } l Multiple catches are ordered so that exception types are listed from the lowest to the highest level in the exception hierarchy

For use of Cleveland State's IST410 Students only 14 Catching an Exception l A catch clause normally provides error handling mechanism l Sometimes we may just dump the exception stack try { int i = getNumber(“234”) } catch (NullPointerException np) { np.printStackTrace(); }....

For use of Cleveland State's IST410 Students only 15 Catching an Exception l Sometimes we may retry the code, note nesting try { int i = getNumber(“234”) } catch (NullPointerException np) { System.out.println(“Number was too big, retry”); try { int j = getNumber(“103”); } catch (NullPointerException np1) { } }....

For use of Cleveland State's IST410 Students only 16 Rethrowing an Exception l Sometimes we may partially handle the exception and then rethrow for some other method to complete handling try { int i = getNumber(“234”) } catch (NullPointerException np) { System.out.println(“Number was too big, retry”); throw np; }.... l Of course, the method then must have a throws clause

For use of Cleveland State's IST410 Students only 17 Orderly Exit from Exception l Sometimes we may want to ensure a trailing action, exception or no exception l finally clause enables us to do just that try { int i = getNumber(“234”) } catch (NullPointerException np) { System.out.println(“Number was too big, retry”); } finally { // exit code }

For use of Cleveland State's IST410 Students only 18 Simple Example public class SimpleException { public static void main(String [] args) { int anIntegerNumber; try { anIntegerNumber = Integer.parseInt(args[0]); } catch (ArrayIndexOutOfBoundsException e) { // args is empty System.out.println("Must specify an argument"); return; } catch (NumberFormatException e) { // args[0] is not an integer System.out.println("Must specify an integer"); return; } finally { System.out.println("This line is printed, error or no error"); } System.out.println("Command line value is "+anIntegerNumber); }

For use of Cleveland State's IST410 Students only 19 Exception from Constructor l Constructor is a method and can throw an exception public class Point { private int x, y; public Point(int x, int y) throws NegativeNumberException { if (x < 0 || y < 0) throw new NegativeNumberException(); this.x = x; this.y = y; }.....

For use of Cleveland State's IST410 Students only 20 Defining one’s own Exception Class l A program can use Exceptions defined in Java Language l A program can define its own exception class l A program defined exception is created by extending an Exception class l For example public class NegativeNumberException extends Exception { // implementation of the class } l You may recall that Exception is a subclass of Throwable l User defined exceptions are always checked exception type

For use of Cleveland State's IST410 Students only 21 Throwable l Throwable is the super class of exception/error conditions l It has 2 constructors m Throwable() m Throwable(String msg) l msg defines the error message with which the error object can be initialized with l The error message can be printed with m getMessage() l getMessage() returns the msg string with which the throwable object was constructed

For use of Cleveland State's IST410 Students only 22 Throwable l It is possible to find out the name of the error object itself using np.getClass().getName() where np Appropriate error object getClass()Returns the class object associated with np getName()Returns the name of the class

For use of Cleveland State's IST410 Students only 23 Sample user-defined Exception class public class NegativeNumberException extends Exception { public NegativeNumberException(String msg) { super(msg); } public NegativeNumberException() { super(); }

For use of Cleveland State's IST410 Students only 24 Extending user-defined Exception class l An use-defined exception class can also extend another user-defined exception class class NegativeIntegerException extends NegativeNumberException { public NegativeIntegerException(String msg) { super(msg); } public NegativeIntegerException() { super(); }

For use of Cleveland State's IST410 Students only 25 Comprehensive examples l TestNumberException.java m notice the source file format l Example from Java in a Nutshell m throwtest.java m MyException.java m MyOtherException.java m MySubException.java

For use of Cleveland State's IST410 Students only 26 Exception and overriding l A method that overrides another method from a superclass must throw m Exactly same exception types as the overriden method; or m Subclasses of exception types thrown by the overriden method; or m A subset of exceptions thrown by the superclass method l Implications m No new Exception can be thrown by the subclass method unless it satisfies at least one of the above conditions l Notice the number of exceptions thrown by the subclass method is not a factor if the conditions above are met

For use of Cleveland State's IST410 Students only 27 Exception and overriding: Examples l Superclass method public void methodOne() throws IndexOutOfBoundsException {... } l Subclass method public void methodOne() throws ArrayIndexOutOfBoundsException {.. } l The overriding method is legal since ArrayIndexOutOfBoundsException is a subclass of IndexOutOfBoundsException

For use of Cleveland State's IST410 Students only 28 Exception and overriding: Examples l Superclass method public void methodOne() throws IndexOutOfBoundsException {... } l Subclass method public void methodOne() throws RuntimeException {.. } l The overriding method is NOT legal since RuntimeException is NOT a subclass of IndexOutOfBoundsException

For use of Cleveland State's IST410 Students only 29 Exception and overriding: Examples l Superclass method public void methodOne() throws Exception {... } l Subclass method public void methodOne() throws ArithmeticException, NullPointerException {.. } l The overriding method is legal since both ArithmeticException and NullPointerException are subclasses Exception

For use of Cleveland State's IST410 Students only 30 Exception and overriding: Examples l Superclass method public void methodOne() throws ArithmeticException, NullPointerException {... } l Subclass method public void methodOne() throws ArithmeticException {.. } l The overriding method is legal since the exception thrown by the subclass method is a proper subset of exceptions thrown by the superclass method