Sadegh Aliakbary Sharif University of Technology Fall 2010.

Slides:



Advertisements
Similar presentations
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Advertisements

Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Yoshi
Lecture 9. 2 Exception  An exception is a unusual, often unpredictable event, detectable by software or hardware, that requires special processing occurring.
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
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.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Handling Errors with Exception (in Java) Project 10 CSC 420.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
CS1020 Data Structures and Algorithms I Lecture Note #6 Exceptions Handling exceptional events.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Exception Handling. Definition  The term exception is shorthand for the phrase "exceptional event.“  An exception is an event, which occurs during the.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
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.
Peyman Dodangeh Sharif University of Technology Spring 2015.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
Peyman Dodangeh Sharif University of Technology Fall 2013.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
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.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
CIS Intro to JAVA Lecture Notes Set 5 26-May-05.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
Section 3.3 Exceptional Situations. 3.3 Exceptional Situations Exceptional situation Associated with an unusual, sometimes unpredictable event, detectable.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Lecture 11 Dr. Eng. Ibrahim El-Nahry Exception Handling.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Advanced Programming in Java
Exceptions In this lecture:
Exceptions: When things go wrong
Chapter 10 – Exception Handling
Advanced Programming in Java
Tirgul 13 Exceptions 1.
Testing and Exceptions
Advanced Programming Behnam Hatami Fall 2017.
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.
Fundamental Error Handling
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.
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.
Java Basics Exception Handling.
Exception Objects An exception is an abnormal condition that arises in a code sequence at rum time. Exception is a way of signaling serious problem.
Presentation transcript:

Sadegh Aliakbary Sharif University of Technology Fall 2010

Agenda Exception Handling Fall 2010Sharif University of Technology2

Watch This Method public static Integer getYear(String day){ String yearString = day.substring(0,4); int year = Integer.parseInt(yearString); return year; } public static void main(String[] args) { String day = "2010/11/29"; Integer year = getYear(day); System.out.println(year); } Fall 2010Sharif University of Technology3

Exceptions What is wrong with it? What if day parameter is not a day representation? day = “salam!” What if day parameter is malformed? Day = “29 Nov 2010” What if day parameter is null? This occasions are called Exception Fall 2010Sharif University of Technology4

Handling Exceptions What to do with exceptions? Exit the program Printing the error on console Returning a special value e.g. -1 Fall 2010Sharif University of Technology5

Important Note Sometimes the method can’t handle the exception effectively What should a method do when an exception occurs? Exit the program? Suppose you are in a desktop application Excel, Word, a game, … Print on console? edu site A game Fall 2010Sharif University of Technology6

Returning a Special Value We can return a special value to report an exception E.g. return null; return -1; return 0; return “”; Why not? Fall 2010Sharif University of Technology7

Why not? There is no return value Return type : void There is no special value There are many exceptions Ambiguity Need for documentation Combination of program code and exception code Fall 2010Sharif University of Technology8

There is no special value public static int minimum(int[] nums ){ int m = Integer.MAX_VALUE; for (int i : nums) { m = Math.min(m, i); } return m; } int[] array = {1,2,-1}; int minimumFound = minimum(array); Fall 2010Sharif University of Technology9

Exception Handling Exception Handling is a framework for handling exceptions It simplifies code Separates business code and exception code Fall 2010Sharif University of Technology10

What is an Exception? Exceptional event Error that occurs during runtime Cause normal program flow to be disrupted Examples ? 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 Fall 2010Sharif University of Technology11

Default Exception Handling Provided by Java runtime Prints out exception description Prints the stack trace Hierarchy of methods where the exception occurred Causes the program to terminate Fall 2010Sharif University of Technology12

Example class DivByZero { public static void main(String a[]) { System.out.println(3/0); } Exception in thread "main" java.lang.ArithmeticException: / by zero at exception.Test2.main(Test2.java:19) Fall 2010Sharif University of Technology13

What Happens 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 This job is called “throwing an exception” Exception object contains information about the error its type the state of the program when the error occurred Fall 2010Sharif University of Technology14

What Happens When an Exception Occurs (2)? The runtime system searches the call stack For a method that contains an exception handler When an appropriate handler is found The runtime system passes the exception to the handler The exception handler catches the exception What if the runtime system can not find an exception handler? Uses the default exception handler Fall 2010Sharif University of Technology15

Fall 2010Sharif University of Technology16

Fall 2010Sharif University of Technology17

Exception Handling in Java public static Integer getYear(String day) { String yearString = day.substring(0, 4); int year = Integer.parseInt(yearString); return year; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a well-formed date: "); String date = scanner.next(); Integer year = getYear(date); System.out.println(year); } Fall 2010Sharif University of Technology18

getYear() public static Integer getYear(String day) throws Exception { if (day == null) throw new Exception("null value"); if (day.length() == 0) throw new Exception("empty value"); if (!matchesDateFormat(day)) throw new Exception("malformed value"); String yearString = day.substring(0, 4); int year = Integer.parseInt(yearString); return year; } private static boolean matchesDateFormat(String input) { return input.matches("\\d\\d\\d\\d/\\d\\d/\\d\\d"); } Fall 2010Sharif University of Technology19

main() public static void main(String[] args) { Scanner scanner = new Scanner(System.in); boolean ok = false; while (ok == false) { System.out.print("Enter a well-formed date: "); String date = scanner.next(); try { Integer year = getYear(date); System.out.println(year); ok = true; } catch (Exception e) { System.out.println(e.getMessage()); } Fall 2010Sharif University of Technology20

Exception Handling Keywords throw throws a new exception throws Declares exception throw try Start a block with exception handling catch Catch the exception Fall 2010Sharif University of Technology21

Benefits of Exception Handling Framework Separating Error-Handling code from “regular” business logic code Propagating errors up the call stack Grouping and differentiating error types Fall 2010Sharif University of Technology22

Fall 2010Sharif University of Technology23

References Fall 2010Sharif University of Technology24