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.

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Advertisements

Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Index Exception handling Exception In Java Exception Types
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.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Io package as Java’s basic I/O system cont’d Reading and Writing Files.
COMP201 Java Programming Topic 6: Exceptions Reading: Chapter 11.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
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.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
1. 2 Examples for Exception?... An exception is an abnormal condition that arises in a code sequence at run time (Run time error). In other computer languages.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
1 Nested Classes O. 2 Possible to declare a class within another class; called nested classes Nested class should have some specific association with.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
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. 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.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exception Error handling. Exception 4 n An unusual occurrence during program execution that requires immediate handling n Errors are the most common type.
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.
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.
Object Oriented Programming
EXCEPTION HANDLING.
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.
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.
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.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Overloading There is another aspect to polymorphism: Overloading Overloading is not overriding. In Turkish: Overridding: eskisini (geçersiz kılmak) Overloading:
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.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
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.
1 cuberoot /* Solve f(x) = x*x*x-5 = 0 f'(x) = 3x^2 */ public class cuberoot{ public static void main(String args[]){ double error= ; double x0.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
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.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
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.
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.
Objectives You should be able to describe: Interactive Keyboard Input
Introduction to Exceptions in Java
Introduction to Exceptions in Java
I/O Basics.
I/O Streams- Basics Byte Streams and Character Streams
Web Design & Development Lecture 7
Lecture 11 Objectives Learn what an exception is.
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.
Exception Handling Contents
Exception Handling.
Presentation transcript:

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 exception is an object that describes an exceptional condition that has occurred in a piece of code When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error An exception can be caught to handle it or pass it on Exceptions can be generated by the Java run-time system, or they can be manually generated by your code

3 Exception-Handling Fundamentals Java exception handling is managed by via five keywords: try, catch, throw, throws, and finally Program statements to monitor are contained within a try block If an exception occurs within the try block, it is thrown Code within catch block catch the exception and handle it System generated exceptions are automatically thrown by the Java run-time system To manually throw an exception, use the keyword throw Any exception that is thrown out of a method must be specified as such by a throws clause

4 Exception-Handling Fundamentals Any code that absolutely must be executed before a method returns is put in a finally block General form of an e xception-handling block try{ // block of code to monitor for errors } catch (ExceptionType1 exOb){ // exception handler for ExceptionType1 } catch (ExceptionType2 exOb){ // exception handler for ExceptionType2 } //… finally{ // block of code to be executed before try block ends }

5 Exception Types All exception types are subclasses of the built-in class Throwable Throwable has two subclasses, they are Exception (to handle exceptional conditions that user programs should catch) An important subclass of Exception is RuntimeException, that includes division by zero and invalid array indexing Error (to handle exceptional conditions that are not expected to be caught under normal circumstances). i.e. stack overflow

6 Uncaught Exceptions If an exception is not caught by user program, then execution of the program stops and it is caught by the default handler provided by the Java run-time system Default handler prints a stack trace from the point at which the exception occurred, and terminates the program Ex: class Exc0 { public static void main(String args[]) { int d = 0; int a = 42 / d; } Output: java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4) Exception in thread "main"

7 Using try and catch Handling an exception has two benefits, It allows you to fix the error It prevents the program from automatically terminating The catch clause should follow immediately the try block Once an exception is thrown, program control transfer out of the try block into the catch block Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism

8 Example Output: Division by zero. After catch statement.

9 Using try and catch A try and catch statement form a unit. The scope of the catch clause is restricted to those statements specified by the immediately preceding try statement You cannot use try on a single statement

10 Multiple catch Clauses If more than one can occur, then we use multiple catch clauses When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed After one catch statement executes, the others are bypassed

11 Example

12 Example (Cont.) If no command line argument is provided, then you will see the following output: a = 0 Divide by 0: java.lang.ArithmeticException: / by zero After try/catch blocks If any command line argument is provided, then you will see the following output: a = 1 Array index oob: java.lang.ArrayIndexOutOfBoundsException After try/catch blocks.

13 Caution Remember that, exception subclass must come before any of of their superclasses Because, a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. So, the subclass would never be reached if it come after its superclass For example, ArithmeticException is a subclass of Exception Moreover, unreachable code in Java generates error

14 Example

15 Nested try Statements A try statement can be inside the block of another try Each time a try statement is entered, the context of that exception is pushed on the stack If an inner try statement does not have a catch, then the next try statement’s catch handlers are inspected for a match If a method call within a try block has try block within it, then then it is still nested try

16 Example

17 Output When no parameter is given: Divide by 0: java.lang.ArithmeticException: / by zero When one parameter is given a = 1 Divide by 0: java.lang.ArithmeticException: / by zero When two parameters are given a = 2 Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException

18 throw It is possible for your program to to throw an exception explicitly throw TrrowableInstance Here, TrrowableInstance must be an object of type Throwable or a subclass Throwable There are two ways to obtain a Throwable objects: Using a parameter into a catch clause Creating one with the new operator

19 Example Output: Caught inside demoproc. Recaught: java.lang.NullPointerException: demo

20 throws If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception type method-name parameter-list) throws exception-list { // body of method } It is not applicable for Error or RuntimeException, or any of their subclasses

21 Example: incorrect program

22 Example: corrected version Output: Inside throwOne. Caught java.lang.IllegalAccessException: demo

23 finally It is used to handle premature execution of a method (i.e. a method open a file upon entry and closes it upon exit) finally creates a block of code that will be executed after try/catch block has completed and before the code following the try/catch block finally clause will execute whether or not an exception is thrown

24 Example

25 Output inside procA procA's finally Exception caught inside procB procB's finally inside procC procC's finally

26 Java’s Built-in Errors Small letter indicate package name Capital letter indicate class name

27 Java’s Built-in Exceptions

28 I/O Basics

29 I/O Basics The io package of Java supports Java’s basic I/O system, including file I/O (java.io ) We have not seen much I/O till now, because most real applications of Java are not text-based, console programs Rather, they are graphically oriented applets that rely upon Java’s Abstract Window Toolkit (AWT) for interaction with the user

30 Streams Java programs perform I/O through streams A stream is an abstraction that either produces or consumes information A stream is linked to a physical device by the Java I/O system. All streams behave the same manner, even if the actual physical devices differs (disk file, keyboard, network socket)

31 Types of streams Java defines two types of streams Byte streams (used to read/write binary data) Character streams (used to read/write characters, its uses Unicode) Byte stream classes: At the top are two abstract classes, InputStream OutputStream Their concrete subclasses handle the differences between various devices and implements (overrides) key abstract methods, such as read( ) and write( )

32

33 Character Stream Classes At the top are two abstract classes, Reader Writer They have also some concrete subclasses that overrides key methods, such as read( ) and write( )

34

35 The Predefined streams java.lang package (automatically imported) defines a class called System System contains three predefined public static stream variables, in, out, and err, which can be accessed from any part of the program without reference to a specific System object System.out refers to standard output stream (console) and System.in refers to standard input (keyboard)

36 Reading Console Input For reading console input, character-oriented stream is preferred To obtain a character-based stream, System.in is wrapped in a BufferedReader object, to create a character stream BufferedReadrer(Reader inputReader) inputReader is the stream that is linked to the instance of BufferedReader that is being created Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters InputStreamReader(InputStream inputStream)

37 Reading Console Input Because System.in refers to an object of type InputStream, it can be used for inputStream Putting it all together: BufferedReader br = new BufferedReader (new InputStreamReader(System.in)); To read character from from BufferedReader, we write, int read( ) throws IOException It reads character from the input stream and returns it as an integer value (return –1 at the end)

38 Example

39 Reading Strings

40