What can go wrong in a Java program while running?

Similar documents
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

Data Structures G5029

COMP1008 Exceptions. Runtime Error

Exceptions and Design

CSCI 261 Computer Science II

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

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

Associate Professor Dr. Raed Ibraheem Hamed

ECE 122. Engineering Problem Solving with Java

Exceptions - Example. Exceptions - Example

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

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Object Oriented Design. Object-Oriented Design. Inheritance & Polymorphism. Class Hierarchy. Goals Robustness Adaptability Flexible code reuse

Lists are great, but. Stacks 2

BBM 102 Introduction to Programming II Spring Exceptions

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions

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

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

Exception Handling CSCI 201 Principles of Software Development

Object-Oriented Design. March 2005 Object Oriented Design 1

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

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

BBM 102 Introduction to Programming II Spring 2017

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

ITI Introduction to Computing II

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Stacks have many uses Arithmetic Language parsing Keeping track of recursion (more in this in a week or so)

G Programming Languages - Fall 2012

ITI Introduction to Computing II

Programming II (CS300)

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

Data Structures. 02 Exception Handling

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Sri Vidya College of Engineering & Technology Question Bank

Object Oriented Programming

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

More on Exception Handling

More on Exception Handling

CS 61B Discussion 5: Inheritance II Fall 2014

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

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

EXCEPTION HANDLING. Summer 2018

Programming II (CS300)

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

CS112 Lecture: Exceptions and Assertions

6.Introducing Classes 9. Exceptions

Programming Languages and Techniques (CIS120)

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

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

Stacks. Common data structures - useful for organizing data for specific tasks Lists Stacks - an Abstract Data Type

Internal Classes and Exceptions

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

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

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

17. Handling Runtime Problems

Correctness and Robustness

Exception-Handling Overview

Data Structures & Algorithm Analysis. Lecturer: Souad Alonazi

15CS45 : OBJECT ORIENTED CONCEPTS

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

Stack Implementation

Chapter 12 Exception Handling

Errors and Exceptions

CS313D: ADVANCED PROGRAMMING LANGUAGE

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

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

Exceptions and Error Handling

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

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

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

Contents. I Introductory Examples. Topic 06 -Exception Handling

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.

CMSC 4023 Chapter 11

1. Stack Implementation Using 1D Array

Exception Handling. Chapter 9

Lecture 19 Programming Exceptions CSE11 Fall 2013

Fundamentals of Object Oriented Programming

Java Errors and Exceptions. Because Murphy s Law never fails

Today. Instance Method Dispatch. Instance Method Dispatch. Instance Method Dispatch 11/29/11. today. last time

CS 209 Programming in Java #10 Exception Handling

CS159. Nathan Sprague

Inheritance. Transitivity

Outline. Example stack Version 1 -- int stack with fixed array Version 2 -- int stack with flexible array Version 3 -- with interface

Arrays Classes & Methods, Inheritance

Lecture No.04. Data Structures

Engineering Abstractions in Model Checking and Testing. Michael Achenbach Klaus Ostermann

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

Lecture Data Structure Stack

Object Oriented Programming

Introduction Unit 4: Input, output and exceptions

Exceptions. Gunnar Gotshalks EX 1

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

CS1020 Data Structures and Algorithms I Lecture Note #8. Exceptions Handling exceptional events

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

Principles of Software Construction: Objects, Design and Concurrency. Exceptions, scope, static data and methods, and Generics.

Recitation 3. 2D Arrays, Exceptions

Transcription:

Exception Handling See https://docs.oracle.com/javase/tutorial/ essential/exceptions/runtime.html See also other resources available on the module webpage

This lecture Summary on polymorphism, multiple inheritance and interfaces Using Java exceptions The clauses throw, try, catch, finally in exception handling Creating your own exceptions Multiple exceptions

What can go wrong in a Java program while running? accessing an object through a null reference. attempting to access an array element through an index that is too large or too small. dividing by zero overflow e.g., exceeding the largest integer that can be represented in Java. retrieving an element from an empty database. etc.

Exception Handling - Why? Think about what can go wrong and deal with it appropriately! Handling these errors is carried out using Exception Handling. Exception handling allows programmers to write clear, more robust, and more fault-tolerant programs. Commercial products usually have more exception handling code than casual software.

Java Exception Handling Java Exception handling follows the following mechanism: Potential errors are dealt with in the vicinity of the code but the code may be polluted with the error processing. A Java programmer can use already defined kinds of exceptions but also define its own exceptions for the problem at hand.

Java Predifined Exceptions In Java, exceptions are classes derived from the class Throwable, which is also extended by Exception. The subclass RuntimeException concerns exceptions that can be thrown during the normal operation of the JVM. The subclass IOException concerns input/output data This forms a kind of hierarchy between the Exception classes. For example, IOException and RuntimeException are 2 sublasses of Exception. See the Java API for more details on the class hierarchy.

How do we define our own exceptions? public class NotNumberException extends Exception { String error; // state variable error message public NotNumberException () { //constructor 1 error = "This is not a valid number"; public NotNumberException ( String s) { //constructor 2 error = s; public String getmessage() { //get method return error;

Throwing Exceptions Exceptions can be thrown within a method function by using the keyword throws. public int intdivision(int num, int denom) throws NotNumberException { if (denom==0) { throw new NotNumberException("Cannot divide by 0"); return num/denom;

Catching Exceptions Exceptions can be caught by using the try-catch construct. public void callintdivision(int a, int b){ try { int res = intdivision(a, b); System.out.println(res); catch (NotNumberException e) { //return the corresponding error message System.out.println(e.getMessage());

Quick Quiz 1 What is the output after the execution of the following code? public int intdivision(int num, int denom) throws NotNumberException { if (denom==0) { throw new NotNumberException("Cannot divide by 0"); return num/denom; try { int res = intdivision(3, 0); System.out.println("result is "+res); catch (NotNumberException e) { System.out.println(e.getMessage()); 1. result is 3 2. Cannot divide by 0 3. result is 0 4. Not a number

Mutliple Catch Blocks public void readinputdata(){ FileReader file = null; try { file = new FileReader("data.txt");//reading from a fil char c = (char) file.read();//reads a char from file catch (FileNotFoundException ex) { // return appropriate error message catch (IOException e) { //return the corresponding error message System.out.println(e.getMessage()); FileNothFoundException is a Java pre-defined class, which deals with file handling e.g., opening or closing a file.

The Finally Block The finally block may be used to release any permanent resources the method might have allocated e.g., closing an open file. public void readinputdata(){ FileReader file = null; try { //code that throws an IOException and FileNotFoundException catch (FileNotFoundException e) { System.out.println(e.getMessage()); catch (IOException ex) { System.out.println(ex.getMessage()); finally { if (file!= null){ try { file.close(); catch (IOException e) { //deals with the exception

Quick Quiz 2 Consider the following code fragment. try { System.out.println("try block"); finally { System.out.println("finally block"); Which of the followings is correct? 1. The given code is illegal. 2. The given code will always throw a runtime error. 3. The given code is syntactically correct. 4. The given code trows an Exception error.

The Stack data structure A stack is commonly used data structure e.g., a pile of plates. It is known as a LIFO (Last-in-First-out) data structure. The insertion operation is known as push The removal operation is called as pop

Stack Operations push() store an element on the stack pop() remove an element from the stack top() get the top element of the stack without removing it isfull() check if stack is full isempty() check if stack is empty

Exercise Write a java code to handle a stack of integers: Use exception handling to write a method that pops an element from a Stack and that deals with the case wherein the stack is empty. Use exception handling to write a method that pushes an element into a stack and that deals with the case wherein the stack is full.

Model answers (1) Quiz 1-2 Quiz 2-3 Java code for the exercise

Model answers (2) public class IntegerStack { private int top; int size; int[] stack; public IntegerStack() { size = 10; stack = new int[10]; top = -1; public IntegerStack(int s) { size = s; stack = new int[size]; top = -1; public int pop() throws StackException { if (isempty()){ throw new StackException("Empty! cannot pop"); int i = stack[top]; top = top-1; return i; public void push(int i) throws StackException { if (isfull()) { throw new StackException("Full!Cannot push "+i); top = top+1; stack[top] = i; public boolean isempty() { return top==-1; public boolean isfull() { return top==size-1;

Model answers (3) public class StackException extends Exception { String error; public StackException () { super(); public StackException (String err) { error = err; public String getmessage() { return error;