Object Oriented Programming Exception Handling

Similar documents
CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Download link: Java Exception Handling

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

ECE 122. Engineering Problem Solving with Java

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Object Oriented Programming

BBM 102 Introduction to Programming II Spring Exceptions

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Programming II (CS300)

Program Correctness and Efficiency. Chapter 2

Exception Handling. Chapter 11. Outline. Example: The Quotient app What Are Exceptions? Java By Abstraction Chapter 11

Fundamentals of Object Oriented Programming

Programming II (CS300)

Exception-Handling Overview

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

C16b: Exception Handling

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

Exceptions - Example. Exceptions - Example

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

BBM 102 Introduction to Programming II Spring 2017

Data Structure. Recitation IV

Reminder. Topics CSE What Are Exceptions?! Lecture 11 Exception Handling

Std 12 Lesson-10 Exception Handling in Java ( 1

Introduction to Programming Using Java (98-388)

Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

Computer Components. Software{ User Programs. Operating System. Hardware

CSCI 261 Computer Science II

CSC 1214: Object-Oriented Programming

Exceptions. What exceptional things might our programs run in to?

School of Informatics, University of Edinburgh

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Java Errors and Exceptions. Because Murphy s Law never fails

Debugging and Handling Exceptions

ITI Introduction to Computing II

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Exceptions in Java

Chapter 10. Exception Handling. Java Actually: A Comprehensive Primer in Programming

CSCI Object Oriented Design: Java Review Errors George Blankenship. Java Review - Errors George Blankenship 1

CSCI Object-Oriented Design. Java Review Topics. Program Errors. George Blankenship 1. Java Review Errors George Blankenship

COMP1008 Exceptions. Runtime Error

Exception Handling. Chapter 11. Java By Abstraction Chapter 11. Outline What Are Exceptions?

ITI Introduction to Computing II

Introduction to Java

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

16-Dec-10. Consider the following method:

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

Exceptions and Design

Here is a hierarchy of classes to deal with Input and Output streams.

Introduction to Software Design

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course

Error Handling in C++

Lecture 07 Debugging Programs with GDB

CS2: Debugging in Java

COMP-202 Unit 9: Exceptions

CS 231 Data Structures and Algorithms, Fall 2016

CS159. Nathan Sprague

Chapter 12 Exception Handling

Chapter 11 Handling Exceptions and Events. Chapter Objectives

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Exception in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

Exceptions. Author: Boaz Kantor The Interdisciplinary Center, Herzliya Introduction to Computer Science Winter Semester

Object Oriented Programming. Week 7 Part 1 Exceptions

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Correctness and Robustness

COMP-202 Unit 9: Exceptions

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. Exception Handling


Introduction Unit 4: Input, output and exceptions

Object Oriented Programming

CS 3 Introduction to Software Engineering. 3: Exceptions

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

Typecasts and Dynamic Dispatch. Dynamic dispatch

EXCEPTION HANDLING. Summer 2018

PROGRAMMING FUNDAMENTALS

Chapter 13 Exception Handling

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

Unit 5 - Exception Handling & Multithreaded

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Pace University. Fundamental Concepts of CS121 1

9. Java Errors and Exceptions

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

Chapter 1 Getting Started

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

National University. Faculty of Computer Since and Technology Object Oriented Programming

Supplemental Handout: Exceptions CS 1070, Spring 2012 Thursday, 23 Feb 2012

Exception Examples. All examples written by Edith Hemaspaandra and modified by Jessica Bayliss

6.Introducing Classes 9. Exceptions

Assertions and Exceptions Lecture 11 Fall 2005

Lecture 22: Java. Overall Structure. Classes & Objects. Every statement must end with ';' Carl Kingsford, , Fall 2015

Selected Java Topics

Computer Science is...

Transcription:

Object Oriented Programming Exception Handling Budditha Hettige Department of Computer Science

Programming Errors Types Syntax Errors Logical Errors Runtime Errors Syntax Errors Error in the syntax of a sequence of characters or tokens that is intended to be written in a particular programming language All syntax errors can be reliably detected until run-time Many Syntax errors can be detected at compile-time 2

Common Java syntax errors Capitalization of key words Line xx: class or interface declaration expected Writing a string over a new line Line xx: ';' expected Forgetting to import a package 3

Logical Errors Errors that indicate the logic used when coding the program failed to solve the problem You do not get error messages with logic errors Your only clue to the existence of logic errors is the production of wrong solutions Debugging is a way to solve logical errors Insert breakpoint(s) Debug your code Check variable values at run time 4

Common Logic Errors in Java Using a variable before it is given a value int x; x = x + 1; System.out.println("X = " + x); Misplaced Semi-colon (usually with a loop or if statement) if ( x > y) ; System.out.println("X is bigger"); Confusing the equivalence operator == with the assignment operator = 5

Runtime Errors low-level errors dereference of a null pointer out-of-bounds array access divide by zero attempt to open a non-existent file for reading bad cast (e.g., casting an Object that is actually a Boolean to Integer) higher-level call to Stack's "pop" method for an empty stack call to "factorial" function with a negative number call to List's nextelement method when hasmoreelements is false 6

Runtime Errors contd.. Errors can arise due to User error providing a bad file name or a poorly formatted input file Enter invalid input (Type) Programmer error These errors should be detected as early as possible to provide good feedback. 7

Exceptions can occur at many levels Hardware/operating system level. Arithmetic exceptions; divide by 0, under/overflow. Memory access violations; segfault, stack over/underflow. Language level. Type conversion; illegal values, improper casts. Bounds violations; illegal array indices. Bad references; null pointers. Program level. User defined exceptions. 8

Way to handle errors Write an error message and quit. This doesn't provide any recovery Return a special value to indicate that an error occurred calling code check for an error. This can reduce the efficiency of the code Use a reference parameter or a global variable to hold an error code Use exceptions. This seems to be the method of choice for modern programming languages. 9

What Is an Exception? An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Example Divide by zero errors Accessing the elements of an array beyond its range Invalid input Hard disk crash Opening a non-existent file Heap memory exhausted 10

Example class DivByZero public static void main(string args[]) System.out.println(3/0); System.out.println( Pls. print me. ); Error Message Exception in thread "main" java.lang.arithmeticexception: / by zero at DivByZero.main(DivByZero.java:3) Divide by zero Where the error is occurred 11

Default exception handler (Java) 1. Provided by Java runtime 2. Prints out exception description 3. Prints the stack trace 4. Hierarchy of methods where the exception occurred 5. Causes the program to terminate Exception in thread "main" java.lang.arithmeticexception: / by zero at DivByZero.main(DivByZero.java:3) 12

When an Exception Occurs? When an exception occurs within a method, the method creates an exception object and hands it off to the runtime system Creating an exception object and handing it to the runtime system is called throwing an exception Exception object contains information about the error, including its type and the state of the program when the error occurred Exception in thread "main" java.lang.arithmeticexception: / by zero at DivByZero.main(DivByZero.java:3) 13

Java Exception Handling A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it. Hence, only the methods that care about errors have to worry about detecting errors Any checked exceptions that can be thrown within a method must be specified in its throws clause 14

Java exception hierarchy 15

Catching Exceptions try <code to be monitored for exceptions> catch (<ExceptionType1> <ObjName>) <handler if ExceptionType1 occurs>... catch (<ExceptionTypeN> <ObjName>) <handler if ExceptionTypeN occurs> 16

Example 17

Multiple catch 18

How try and catch works? NO Match Try Catch Catch Statement after the last catch Leaves the method 19

Example 1. Execute This 2. Go to this catch() 3. Execute This 20

Catching Exceptions with finally Syntax: try <code to be monitored for exceptions> catch (<ExceptionType1> <ObjName>) <handler if ExceptionType1 occurs>... finally <code to be executed before the try block ends> 21

Catching Exceptions the finally Keyword Block of code is always executed despite of different scenarios: Forced exit occurs using a return, a continue or a break statement Normal completion Caught exception thrown Exception was thrown and caught in the method Uncaught exception thrown Exception thrown was not specified in any catch block in the method 22

How try and catch finaly works? Try Catch Catch NO Match Finally() Statement after the last catch 23

Throwing Exceptions Java allows you to throw exceptions (generate exceptions) throw <exception object>; An exception you throw is an object You have to create an exception object in the same way you create any other object Example: throw new ArithmeticException( testing... ); 24