Exceptions Handeling

Similar documents
Exception with arguments

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

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

CMSC 202. Exceptions

Comp 249 Programming Methodology Chapter 9 Exception Handling

Introduction to Computer Science Unit 2. Notes

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

CS 231 Data Structures and Algorithms, Fall 2016

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

Object Oriented Programming

Lecture (01) Getting started. Dr. Ahmed ElShafee

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

Fundamentals of Programming II Lab 06

Fundamentals of Programming Data Types & Methods

BBM 102 Introduction to Programming II Spring Exceptions

Midterm Examination (MTA)

Exception-Handling Overview

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

while (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */

Example Program. public class ComputeArea {

Chapter 1 Lab Algorithms, Errors, and Testing

Web-CAT submission URL: CAT.woa/wa/assignments/eclipse

Chapter 5 Lab Methods

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

About this exam review

Chapter 12 Exception Handling

COMP 110 Project 1 Programming Project Warm-Up Exercise

Session 04 - Object-Oriented Programming 1 Self-Assessment

Fundamentals of Object Oriented Programming

CAT.woa/wa/assignments/eclipse

Programming II (CS300)

CSC 1214: Object-Oriented Programming

Programming with Java

Introduction to Computer Science Unit 2. Notes

Advanced Java Concept Unit 1. Mostly Review

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

STUDENT LESSON A5 Designing and Using Classes

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

In this lab we will practice creating, throwing and handling exceptions.

Programming II (CS300)

Object Oriented Programming. Java-Lecture 6 - Arrays

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Java Errors and Exceptions. Because Murphy s Law never fails

Objectives: Lab Exercise 1 Part 1. Sample Run. Part 2

When we reach the line "z = x / y" the program crashes with the message:

Loops. CSE 114, Computer Science 1 Stony Brook University

Pace University. Fundamental Concepts of CS121 1

Object-Oriented Programming in Java

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

CS61BL. Lecture 1: Welcome to CS61BL! Intro to Java and OOP Testing Error-handling

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Testing and Debugging

Std 12 Lesson-10 Exception Handling in Java ( 1

Lab 9: Creating a Reusable Class

CSC 1051 Data Structures and Algorithms I

BBM 102 Introduction to Programming II Spring 2017

Program Control Flow

Program Control Flow

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

10/3/2018 Programming Data Structures. Casting: upcasting, downcasting Debugging again! Yay! Exception Handling

CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.

Final Examination Semester 3 / Year 2008

Introduction to Java. Handout-1d. cs402 - Spring

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

AP Computer Science Unit 1. Writing Programs Using BlueJ

Java Coding 3. Over & over again!

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

Advanced Computer Programming

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

CS159. Nathan Sprague

1.00 Lecture 8. Using An Existing Class, cont.

Internal Classes and Exceptions

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

CSC 1051 Data Structures and Algorithms I

Lab Exercise 1. Objectives: Part 1. Introduction

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 11

9. Java Errors and Exceptions

Elementary Programming

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

Building Java Programs

Chapter 5 Lab Methods

Chapter 4: Conditionals and Recursion

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

this keyword (1). this with constructor (2). cisc3120 design and implementation of software applications I spring 2015 lecture # I.

Chapter 4: Loops and Files

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Methods

2.2 - Making Decisions

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG


CSCI 1103: File I/O, Scanner, PrintWriter

Arrays. Eng. Mohammed Abdualal

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

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Arrays

Software Design and Analysis for Engineers

Transcription:

Exceptions Handeling Dr. Ahmed ElShafee Dr. Ahmed ElShafee, Fundamentals of Programming II, ١ Agenda 1. * 2. * 3. * ٢ Dr. Ahmed ElShafee, Fundamentals of Programming II,

Introduction During the execution of a program, the computer will face two types of situations: those it is prepared to deal with and those it is not. Imagine you write a program that requests a number from the user: ٣ import java.util.scanner; public class Exercise { public static void main(string[] args) { double side; Scanner scnr = new Scanner(System.in); System.out.println("Square Processing"); System.out.print("Enter Side: "); side = scnr.nextdouble(); System.out.println("\nSquare Characteristics"); System.out.printf("Side: %.2f\n", side); System.out.printf("Perimeter: %.2f\n", side * 4); This is a classic easy program. When it comes up, the user is asked to simply type a number. The number would then be multiplied by 4 and display the result. Square Processing Enter Side: 24.95 Square Characteristics Side: 24.95 Perimeter: 99.80 Imagine that a user types something that is not a valid number, such as the name of a country or somebody s telephone number. Since this program was expecting a number and it is not prepared to multiply a string to a number, it would not know what to do. ٤ Dr. Ahmed ElShafee, Fundamentals of Programming II,

The only alternative the compiler would have is to send the problem to the operating system, hoping that the OS would know what to do. What actually happens is that, whenever the compiler is handed a task, it would try to perform the assignment. If it cannot perform the assignment, for any reason it is not prepared for, it would produce an error. As a programmer, if you can anticipate the type of error that could occur in your program, you can identify the error yourself and deal with it by telling the compiler what to do when this type of error occurs. ٥ Dr. Ahmed ElShafee, Fundamentals of Programming II, Lecture0801 ٦ Dr. Ahmed ElShafee, Fundamentals of Programming II,

Lecture0802 ٧ Dr. Ahmed ElShafee, Fundamentals of Programming II, trying An exception is an unusual situation that could occur in your program. As a programmer, you should anticipate any abnormal behavior that could be caused by the user entering wrong information that could otherwise lead to unpredictable results. The ability to deal with a program s abnormal behavior is called exception handling. Java provides many keywords and built in classes to handle an exception. ٨ Dr. Ahmed ElShafee, Fundamentals of Programming II,

To start handling an exception, create a section of code that includes the normal flow of the program. This section starts with the try keyword followed by an opening curly bracket and a closing curly bracket. The section in the curly brackets is the body. In it, you write ٩ the normal code. public static void main(string[] args) { double side; Scanner scnr = new Scanner(System.in); try { System.out.println("Square Processing"); System.out.print("Enter Side: "); side = scnr.nextdouble(); System.out.println("\nSquare Characteristics"); System.out.printf("Side: %.2f\n", side); System.out.printf("Perimeter: %.2f\n", side * 4); Catching Just after the try section, that is, after the closing curly bracket of try, you create a new section that uses the catch keyword. catch(exceptionclass) { WhatToDo As you can see, this section starts with the catch keyword with parentheses. The parentheses behave like those of a method. You must pass an argument. At a minimum, you can pass a class named Exception and a name for the argument. After the closing the parenthesis, create a body for the section. Like a normal body, this starts with an opening curly bracket and ends with a closing curly bracket.

Based on this, the basic formula of exception handling is: try { // Try the program flow catch(exception arg) { // Catch the exception ١١ Dr. Ahmed ElShafee, Fundamentals of Programming II, Lecture0803 ١٢ Dr. Ahmed ElShafee, Fundamentals of Programming II,

Lecture0804 ١٣ Dr. Ahmed ElShafee, Fundamentals of Programming II, Do something with caught error As mentioned already, if an error occurs when processing the program in the try section, the compiler transfers the processing to the next catch section. You can then use the catch section to deal with the error. At a minimum, you can display a message to inform the user. ١٤ Dr. Ahmed ElShafee, Fundamentals of Programming II,

Lecture0805 ١٥ Dr. Ahmed ElShafee, Fundamentals of Programming II, Lecture0806 ١٦ Dr. Ahmed ElShafee, Fundamentals of Programming II,

Lecture0807 ١٧ Dr. Ahmed ElShafee, Fundamentals of Programming II, Exception Throwing Imagine you write a program that requests a student s age from the user. As we know, everybody s age is positive. Therefore, we need to figure out what to do if the user types a negative number. The expression that checks whether the number entered is positive can be written as if(studentage < 0) ١٨ Dr. Ahmed ElShafee, Fundamentals of Programming II,

Lecture0808 ١٩ Dr. Ahmed ElShafee, Fundamentals of Programming II, To throw an exception, you use the throw keyword. The primary formula of using this keyword is: try { Normal flow When to throw the exception throw What? catch(exception e) { // Deal with the exception here The new keyword in this formula is throw. On the right side of throw, indicate to the compiler what to do. This means that the throw keyword is followed by an ٢٠ expression.

In our introduction to exceptions, we got acquainted with the Exception class. Besides the default constructor, the Exception class is equipped with another constructor that takes a string as argument. When using the throw keyword, you can use this constructor to specify a message to display to display in case of an error. To do this, use the new operator to call the constructor and pass a message to it. ٢١ Dr. Ahmed ElShafee, Fundamentals of Programming II, public class Exercise { public static void main(string[] args) { int studentage = 0; Scanner scnr = new Scanner(System.in); try { System.out.print("Student Age: "); studentage = scnr.nextint(); if( studentage < 0 ) throw new Exception("Positive Number Required"); System.out.println("Student Age: " + studentage); catch(exception exc) { System.out.println("Error: " + exc.getmessage()); ٢٢

If the user enters an invalid value, the program examines the throw keyword. This throw appears to display a string. The compiler registers this string and since there was an exception, the program exits the try block (it gets out of the try block even if the rest of the try block is fine) and looks for the first catch block it can find. If it finds a catch that does not take an argument, it would still use the catch. Otherwise, you can use the catch block to display the error string that was sent by the throw keyword. ٢٣ Dr. Ahmed ElShafee, Fundamentals of Programming II, Lecture0809 check lab manual ٢٤ Dr. Ahmed ElShafee, Fundamentals of Programming II,

Lecture0810 ٢٥ Dr. Ahmed ElShafee, Fundamentals of Programming II, Catching Multiple Exceptions The programs we have seen so far dealt with a single exception. Most of the time, a typical program will use different types of errors. Fortunately, you can deal with as many errors as possible. To do this, you can create a catch block for each (type of) error try { Code to Try catch(arg1) { One Exception catch(arg2) { Another Exception ٢٦ Dr. Ahmed ElShafee, Fundamentals of Programming II,

1. The compiler enters the try block and follows the normal flow of the program 2. If no exception occurs in the try block, the rest of the try block is executed. 3. If an exception occurs in the try block, the try displays a throw expression that specifies the type of error that happened. a. The compiler gets out of the try block and examines the first catch b. If the first catch does not match the thrown error, the compiler switches to the next catch. This continues until the compiler finds a catch that matches the thrown error. ٢٧ Dr. Ahmed ElShafee, Fundamentals of Programming II, c. If one of the catches matches the thrown error, its body executes. d. If no catch matches the thrown error, you have (or the compiler has) two alternatives. If there is no catch that matches the error (which means that you did not provide a matching catch), the compiler hands the program flow to the operating system. Another alternative is to include a catch whose argument is the Exception default constructor. ٢٨ Dr. Ahmed ElShafee, Fundamentals of Programming II,

The catch(exception) is used if no other catch, provided there was another, matches the thrown error. The catch(exception), if included as part of a catch clause, must always be the last catch, unless it is the only catch of the clause. Multiple catches are written if or when a try block is expected to throw different types of errors. Imagine a program that requests some numbers from the user and performs some operation on the numbers. ٢٩ Dr. Ahmed ElShafee, Fundamentals of Programming II, byte studentage = 0; Scanner scnr = new Scanner(System.in); try { System.out.print("Student Age: "); studentage = scnr.nextbyte(); if (studentage < 0) { throw new Exception("Positive Number Required"); System.out.println("Student Age: " + studentage); catch (InputMismatchException exc) { System.out.println("The operation could not be carried because " + "the number you typed is not valid"); catch (Exception exc) { System.out.println("Error: " + exc.getmessage()); ٣٠ Dr. Ahmed ElShafee, Fundamentals of Programming II,

Lecture0811 ٣١ Dr. Ahmed ElShafee, Fundamentals of Programming II, Lecture0812 ٣٢ Dr. Ahmed ElShafee, Fundamentals of Programming II,

Nesting Exceptions Like a conditional statement or a class, you can create one exception inside of another Try{ statment,; throw new Exception( message ); Try { statement; throw new exception( message ); Cacth (Excpetion e) { System.Out.print(e.message()); Catch (Exception e){ System.out.print(e.message()); ٣٣ Dr. Ahmed ElShafee, Fundamentals of Programming II, Lecture0813 ٣٤ Dr. Ahmed ElShafee, Fundamentals of Programming II,

Exceptions and Methods One of the ways you can use methods in exception handling is to have a central method that dispatches assignments to other methods. The other methods can use the values of variables; for example they can test. If an exception occurs, the other method can display a message or throw an exception. This throwing can be picked up by the central method that sent the variable. The method that originated the trying can hand it to a catch block or one of the catch blocks in the calling method that can handle the exception. ٣٥ Dr. Ahmed ElShafee, Fundamentals of Programming II, This means that you can create a method that only throws an exception but does not necessarily deal with it. Besides writing code that throws an exception, to indicate to the compiler that a method is throwing an exception, after it closing parenthesis, type the throws keyword followed by the class name of the type of exception that will be thrown Return_type method_name() throws Exception{ ٣٦ Dr. Ahmed ElShafee, Fundamentals of Programming II,

Lecture0814 ٣٧ Dr. Ahmed ElShafee, Fundamentals of Programming II, Lecture0815 ٣٨ Dr. Ahmed ElShafee, Fundamentals of Programming II,

In reality, even if a method does not explicitly throw an exception, you can still include a throws Exception expression to it if you want, in anticipation to a bad behavior. There is a rule you must follow. If a method has code that throws a general exception of type Exception, you must add a throws Exception expression to it. If you violate this rule, the program will not compile. But If a method has code that throws a specific exception of type Exception, (InputMismatchException) you don t have to add a throws Exception expression to it ٣٩ Dr. Ahmed ElShafee, Fundamentals of Programming II, private static double getside() { double side = 0; Error Scanner scnr = new Scanner(System.in); System.out.println("Square Processing"); System.out.print("Enter Side: "); side = scnr.nextdouble(); if( side < 0 ) throw new Exception("Positive number required"); return side; ٤٠ Dr. Ahmed ElShafee, Fundamentals of Programming II,

private static double getside() { double side = 0; OK Scanner scnr = new Scanner(System.in); System.out.println("Square Processing"); System.out.print("Enter Side: "); side = scnr.nextdouble(); if( side < 0 ) throw new InputMismatchException("Positive number required"); return side; ٤١ Dr. Ahmed ElShafee, Fundamentals of Programming II, private static double getside() throws Exception { double side = 0; OK Scanner scnr = new Scanner(System.in); System.out.println("Square Processing"); System.out.print("Enter Side: "); side = scnr.nextdouble(); if( side < 0 ) throw new Exception("Positive number required"); return side; ٤٢ Dr. Ahmed ElShafee, Fundamentals of Programming II,

Lecture0816 ٤٣ Dr. Ahmed ElShafee, Fundamentals of Programming II, Lecture0817 ٤٤ Dr. Ahmed ElShafee, Fundamentals of Programming II,

Thanks, See you next Lecture, isa Dr. Ahmed ElShafee, Fundamentals of Programming II, ٤٥