ruby異常處理:rescue

來源:互聯網
上載者:User

一個運行著的程式常會遇到意外的問題.一個要讀取的檔案不存在;當希望存入一些資料時磁碟滿了;用 戶可能輸入不恰當的資料.

ruby> file = open("some_file")

ERR: (eval):1:in `open': No such file or directory - some_file

一個健壯的程式會合理並漂亮的處理這些問題.面對那些異常是一件討人厭的工作.C程式員被要求做到 檢查每一個可能導致錯誤發生的系統調用的傳回值並立刻做出決定.

FILE *file = fopen("some_file", "r");if (file == NULL) {fprintf( stderr, "File doesn't exist.\n" );exit(1);}bytes_read = fread( buf, 1, bytes_desired, file );if (bytes_read != bytes_desired ) {/* do more error handling here ... */}...

這項無聊的工作會使程式員最終變得馬虎並忽略掉它,結果是程式無法應對異常.令一方面,這樣也會降 低程式的可讀性.因為過多的錯誤處理使有意義的代碼也變得雜亂了.

在Ruby裡,就像其它的現代語言,我們可以通過隔離的辦法處理代碼域裡的異常,因此,這有著驚人的效 果卻又不會為程式員或以後希望讀它的其它人造成過度的負擔.代碼域由begin開始直到遇到一個異常,這 將導致轉向一個由rescue標記的錯誤處理代碼域.如果異常沒發生,rescue代碼就不會使用.下面的代碼返 迴文本檔案的第一行,如果有異常則返回 nil.

def first_line( filename )beginfile = open("some_file")info = file.getsfile.closeinfo # Last thing evaluated is the return valuerescuenil # Can't read the file? then don't return a stringendend

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.