2010-03-24 18 views
7

आर 6 आरएस योजना में अपवादों को फेंकने और पकड़ने का मानक तरीका क्या है? मैं वाक्यविन्यास की तलाश में हूं जो योजना के किसी भी संस्करण (केवल पीएलटी नहीं) में काम करता है जो आर 6 आरएस लागू करता है।आर 6 आरएस योजना में अपवादों को फेंकने और संभालने के लिए कैसे करें

R6RS guard syntax ऐसा लगता है कि यह बिल फिट हो सकता है, लेकिन क्या कोई मुझे वास्तव में इसका उपयोग करने का उदाहरण दिखा सकता है?

उत्तर

7

guard के शब्दों है:

(guard (exception-object 
     ((condition-1-to-test-exception-object) (action-to-take) 
     ((condition-2-to-test-exception-object) (action-to-take) 
     ((condition-N-to-test-exception-object) (action-to-take) 
     (else (action-for-unknown-exception))) 

वहाँ एक सहायक else खंड है कि हम यहाँ का उपयोग नहीं करते है। निम्नलिखित नमूना अपवादों को अनुकरण करता है जिन्हें ठेठ फ़ाइल आईओ संचालन द्वारा उठाया जा सकता है। हम एक guard स्थापित अपवाद को संभालने के लिए:

(define mode 0) 

(define (open-file) 
    (if (= mode 1) 
     (raise 'file-open-error) 
     (display "file opened\n"))) 

(define (read-file) 
    (if (= mode 2) 
     (raise 'file-read-error) 
     (display "file read\n"))) 

(define (close-file) 
    (if (= mode 3) 
     (raise 'file-close-error) 
     (display "file closed\n"))) 

(define (update-mode) 
    (if (< mode 3) 
     (set! mode (+ mode 1)) 
     (set! mode 0))) 

(define (file-operations) 
    (open-file) 
    (read-file) 
    (close-file) 
    (update-mode)) 

(define (guard-demo) 
    (guard (ex 
      ((eq? ex 'file-open-error) 
      (display "error: failed to open file ") 
      (update-mode)) 
      ((eq? ex 'file-read-error) 
      (display "error: failed to read file ") 
      (update-mode)) 
      (else (display "Unknown error") (update-mode))) 
     (file-operations))) 

टेस्ट रन:

> (guard-demo) 
file opened 
file read 
file closed 
> (guard-demo) 
error: failed to open file 
> (guard-demo) 
file opened 
error: failed to read file 
> (guard-demo) 
file opened 
file read 
Unknown error 
> (guard-demo) 
file opened 
file read 
file closed 

अपवाद R6RS की Chapter 7 में उदाहरण कोड के साथ निपटने का विस्तृत विवरण नहीं है।

+0

धन्यवाद - यह वही है जो मैं ढूंढ रहा था। –

संबंधित मुद्दे