مظفر بگ محمدی دانشگاه ایلام

Slides:



Advertisements
Similar presentations
Exception Handling – illustrated by Java mMIC-SFT November 2003 Anders P. Ravn Aalborg University.
Advertisements

CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
CS102--Object Oriented Programming
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Exception Handling By: Thomas Fasciano. What is an Exception?  An error condition that occurs during the execution of a Java Program.
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.
MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?
1 Classes Object-oriented programming: Model the problem as a collection of objects that have certain attributes and interact with one another and/or the.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
Exception handling Dealing with life’s little surprises.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
LAB 10.
Introduction to Computer Programming Error Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Console Input. So far… All the inputs for our programs have been hard-coded in the main method or inputted using the dialog boxes of BlueJ It’s time to.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
CSc2310 tutoring session, week 8 Fall, 2012 Haidong Xue 5:30pm—8:30pm 10/23/2012 and 10/24/2012 -Using Exceptions -Homework 4.
Class Design: Handling Errors Reading: 2 nd Ed: Chapter 15 3 rd Ed: Chapter 11 Exercises 2 nd Ed: P15.5, P15.6 (Hint: look at documentation for Scanner.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
ACO 101: Introduction to Computer Science Anatomy Part 2: Methods.
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.
Introduction to Programming G50PRO University of Nottingham Unit 11 : Files Input/Ouput Paul Tennent
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in.
1 Advanced Flow of Control : Introduction This chapter focuses on: –exception processing –catching and handling exceptions –creating new exceptions –exception.
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Creating a GUI Class An example of class design using inheritance and interfaces.
LECTURE 8: EXCEPTIONS CSC 212 – Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May.
Computer Programming Lab 9. Exercise 1 Source Code package excercise1; import java.util.Scanner; public class Excercise1 { public static void main(String[]
import java.util.Scanner; class myCode { public static void main(String[] args) { Scanner input= new Scanner(System.in); int num1; System.out.println(“Enter.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
2.4 Exceptions n Detects try { //code that may raise an exception and/or set some condition if (condition) throw exceptionName; //Freq. A string } n Handles.
CSE 1201 Object Oriented Programming
TemperatureConversion
Chapter 10 – Exception Handling
Logger, Assert and Invariants
Introduction to Exceptions in Java
Maha AlSaif Maryam AlQattan
CS1101: Programming Methodology Recitation 7 – Exceptions
Introduction to Exceptions in Java
Testing and Exceptions
Handling Exceptions.
EE422C Software Implementation II
Exceptions & exception handling
CMSC 202 Exceptions.
Exceptions & exception handling
COMPUTER 2430 Object Oriented Programming and Data Structures I
مظفر بگ محمدی دانشگاه ایلام
Abdulmotaleb El Saddik University of Ottawa
Exception Handling in Java
Exercise 11.1 Write a code fragment that performs the same function as the statement below without using the crash method Toolbox.crash(amount < 0,
Fundamental Error Handling
More on Classes and Objects
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Exception Handling in Java
Chapter 9 Exception Handling
CMSC 202 Exceptions 2nd Lecture.
Introduction to Object-Oriented Programming
Exceptions.
Exceptions.
CMSC 202 Exceptions.
Basic Exception Handling
Presentation transcript:

مظفر بگ محمدی دانشگاه ایلام استثناء ۱ مظفر بگ محمدی دانشگاه ایلام

رسیدگی به خطاها در یک جهان ایده آل، تمام خطاها در هنگام کامپایل کد اتفاق می افتند و رفع می شوند. لذا هنگام اجرا خطایی رخ نمی دهد. اما در واقعیت اینطور نیست. خطاها هنگام اجرای کد اتفاق می افتند و باید توسط مکانیسمی مورد رسیدگی قرار گیرند که: به تولید کننده (یا تشخیص دهنده) ی خطا اجازه می‌دهد که اطلاعات خطا را به گیرنده ی خطا ارسال نماید و این گیرنده است که می داند با خطا چکار کند.

روش رسیدگی به خطاها در C #define DEPOSIT_NEGATIVE -1 #define DEPOSIT_OK 0 int VerifyDeposit(int amount) { if (amount < 0 ) return DEPOSIT_NEGATIVE; else return DEPOSIT_OK } int depositStatus = VerifyDeposit(amt); if (depositStatus == DEPOSIT_OK) } // do something good } else { // deal with the error

روش بهتر رسیدگی به خطا تفکیک تشخیص خطا از رسیدگی به خطا پیاده کننده ی کلاس خطاها را تشخیص می دهد. کاربر کلاس تصمیم می گیرد که با خطا چکار کند. خروج از برنامه چاپ پیغام مناسب و ادامه ی برنامه اجرای مجدد متد دارای خطا سوال از کاربر یا هر کار مناسب دیگر کاهش پیچیدگی کد کد عادی برنامه که اگر اتفاق ناجوری نیفتد کار خواهد کرد ، از کدی که به خطاها رسیدگی می کند جدا شده است. زبان جاوا برنامه نویس را مجبور می کند که به خطا رسیدگی کند.

try-throw-catch روش پایه ی رسیدگی به خطاها در جاوا استفاده از سه گانه ی try-throw-catch است.

مثال try-throw-catch Scanner in = new Scanner( System.in); System.out.println( “Enter Amt: “); try { int amt = in.nextInt( ); if (amt < 0) throw new Exception( “Negative value was input”); System.out.println (“Thanks for your deposit”); // more code that assumes the amt is not negative } catch( Exception e ) { // do something about the exception System.out.println( “Have a nice day”);

بلوک try کدی که ممکن است استثنا تولید کند در داخل بلوک try قرار می گیرد. بلوک try شامل کد اصلی الگوریتم یا برنامه ی کاربر است. این بلوک روند درست انجام کار را مشخص می کند. کدی که به خطا رسیدگی می کند در داخل بلوک catch قرار می گیرد. بلوک catch بلافاصله بعد از بلوک try قرار دارد.

مثالthrow وقتی که کد برنامه خطا را تشخیص داد یک شی از نوع استثنا را گسیل می کند. public class BankAccount { private int balance; public BankAccount( ) { balance = 0; } public int getBalance( ) { return balance; } // precondition – amount must be nonnegative // throws an exception if amount is negative // postcondition – balance updated public int deposit( int amt ) throws Exception { if (amt < 0 ) throw new Exception(“Deposit is Negative” ); balance += amt;

کد درست سپرده گذاری در بانک public class DepositExample { public static void main( String[ ] args ) { BankAccount myAccount = new BankAccount( ); try { Scanner input = new Scanner( System.in ); System.out.print(“Enter deposit amount: “); int amt = input.nextInt(); myAccount.deposit( amt ); System.out.println( “New Balance = “ + myAccount.getBalance()); } catch (Exception e) { // code that “handles” a negative deposit System.out.println( e.getMessage( )); System.out.println( “GoodBye” );

مکانیسم try-throw-catch هنگام گسیل استثنا، اجرای کد بلوک try متوقف می شود و اجرا به بلوک catch منتقل می شود. مقدار گسیل شده همان پارامتر دستور throw است و یک شی از کلاس استثنا است. بلوک catch یک پارامتر دارد که از طریق دستور throw برای آن گسیل می شود. اجرای بلوک catch همان عمل رسیدگی به استثنا است. 10

مکانیسم try-throw-catch catch( Exception e ) { . . . } شناسه ی e در سرآیند بلوک catch همان پارامتر بلوک catchاست. پارامتر بلوک catch دو کاربرد دارد: مشخص کردن نوع استثنای گسیل شده (در مثال فوق Exception ) نامگذاری استثنا (در مثال فوق همان e). می توان به جای e از هر اسم دیگری استفاده کرد. 11

try-catch Control Flow { // code that might throw an Exception // more code } حالت 1 بلوک try استثنایی تولید نمی کند. بعد از اتمام اجرای بلوک try، کد بلوک catch را نادیده می گیریم. catch(Exception e) { // handle error here } // Method continues here

try-catch Control Flow { throw new Exception( “message”); // more code } حالت 2 بلوک try یک استثنا تولید می کند. اجرای بلوک try متوقف می شود. اجرای بلوک catch شروع می شود. بعد از اتمام اجرای بلوک catch، بقیه ی برنامه اجرا می شود. catch(Exception e) { // handle error here } // Method continues here

کلاسهای Exception زبان جاوا کلاسی به اسم Exception تعریف کرده است. در کتابخانه های جاوا کلاسهای استثنای دیگری نیز وجود دارند. برنامه نویس می تواند کلاس استثنای جدیدی تعریف کند. تمام کلاسهای استثنای تعریف شده توسط جاوا دو خاصیت دارند: یک جزء سازنده دارند که آرگومان آن از نوع رشته است. یک متد به اسم getMessage دارند که رشته ی ارسال شده به کلاس استثنا در هنگام ساخت شی را بر می گرداند. کلاسهای استثنای تعریف شده توسط برنامه نویس نیز باید این خاصیتها را داشته باشند. 14

کلاس Exception کلاس Exception ریشه ی بقیه ی کلاسهای استثنا است. کلاس Exception در بسته ی java.lang قرار دارد که نیازی به import ندارد. 15

استفاده از متد getMessage . . . // method code try { . . . throw new Exception( StringArgument ); } catch(Exception e) String message = e.getMessage(); System.out.println(message); System.exit(0); } . . . 16

استفاده از متد getMessage هر استثنا یک متغییر نمونه از نوع رشته دارد که شامل یک پیغام است. این پیغام دلیل خطا را مشخص می کند. در مثال قبلی، StringArgument آرگومان جزء سازنده ی Exception است. می توان با دستور e.getMessage() مقدار این رشته را از استثنای e استخراج کرد. 17

حفظ خاصیت های getMessage یا اگر جز سازنده ی بدون آرگومان صدا زده شود، باید از پیغام پیش فرض استفاده شود. لذا در کلاسهای استثنای تعریف شده توسط کاربر: باید یک جزء سازنده وجود داشته باشد که یک رشته بعنوان آرگومان بپذیرد و بدنه ی آن با فراخوانی super شروع شود. یک جزء سازنده ی بدون آرگومان باید وجود داشته باشد که super را فراخوانی کند. متد super حتما باید یک آرگومان از نوع رشته داشته باشد. 18

A Programmer-Defined Exception Class 19

نکته: کلاس استثنا می تواند غیر از رشته متغییرهای دیگری نیز داشته باشد. می توان جز سازنده ای داشت که آرگومان آن از نوع رشته نباشد. مقدار را در یک متغییر نمونه ذخیره می کنیم. برای این متغییر خصوصی باید متد دسترسی (get) را تعریف کنیم. 20

یک کلاس استثنا با پیغام int 21

سازنده ها و استثناها اگر پارامتر نادرستی به یک جزء سازنده ارسال شود، می توانیم یک استثنا تولید کنیم. public class BankAccount { private int balance; public BankAccount( int startingBalance ) throws Exception { if (startingBalance < 0) throw new BadNumberException( startingBalance ); balance = startingBalance; }

trying constructors public class BankAccountDemo { public static void main( String[ ] args ) { BankAccount myAccount; // outside the try block??? try { Scanner in = new Scanner( System.in ); System.out.print( “Input starting balance: “ ); int startBalance = in.nextInt( ); myAccount = new BankAccount( startBalance ); // more of the good stuff here } catch (BadNumberException bne ) { // handle the bad input System.out.println(“Deposits must be postive”); Sysetem.out.println(“You entered “ + bne.getBadNumber()); System.out.println( “good bye “);