本文為大家分析了javascript中try...catch...finally的使用方法,分享給大家供大家參考,具體內(nèi)容如下
稍微復雜一點點,就要用到判斷語句,if else進行條件判斷,話說if條件else否則,這樣的判斷對于寫程序代碼的碼儂已經(jīng)是非常熟悉不過了。
如果你覺得這個也很簡單,可能會用到混合if else條件判斷語句加上try catch 來處理語句,雖然用try catch能處理任何的對象,通過throw扔一條有錯誤的語句,接著catch拋出該對象或者該對象的錯誤,今天我們只說try...catch,下面的例子分別拋出數(shù)組、時間、原型函數(shù)、數(shù)字類型等。
function trycatch () { var array = [234], newdate = new Date(), fun = function(){}, is = 12.22, call; try{ throw array + '/n' + newdate.toLocaleString() + ' /n' + fun.prototype.constructor + '/n' + (typeof is == 'number') +' /n' + call ; //小心local后面還有一個'e' } catch(e){ console.log(e); } finally{ console.log('err finally'); }}trycatch () // 輸出:// 234// 2015/10/12 下午10:07:03 // function (){}// true // undefined
更準確的說,try內(nèi)放一條可能產(chǎn)生錯誤的語句。當try語句開始執(zhí)行并拋出錯誤時,catch才執(zhí)行內(nèi)部的語句和對應的try內(nèi)的錯誤信息message。何時執(zhí)行finally語句,只有當try語句和catch語句執(zhí)行之后,才執(zhí)行finally語句,不論try拋出異常或者catch捕獲都會執(zhí)行finally語句。
function trycatch () { try{ throw new Error('koringz'); } catch(e){ console.log(e.message); } finally{ console.log('err finally'); }}trycatch ()// 輸出:// koringz// err finally
通過try扔出一條錯誤的語句,我們看到在catch捕獲到一條錯誤的的信息// koringz,但是同樣的finally也輸出了// err finally。雖然我們了解try catch工作流的處理方式,但是并不了解finally塊的代碼處理程序,按照以往我們對finally語句一貫的思維方式,就是finally輸出不受try和catch的限制和約束。以下是finally的幾個輸出演示代碼:
function trycatch () { try{ throw new Error('koringz'); } finally{ console.log('err finally'); return console.log('new finally') }}trycatch ()// err finally// new finally
如上所示,try扔一條錯誤的語句,finally輸出的結(jié)果是: // err finally // new finally。
function trycatch () { try{ throw new Error('koringz'); } catch(e){ console.log('err finally'); return console.log('new finally') }}trycatch ()// err finally// new finally
如上所示,try扔一條錯誤的語句,catch捕獲到錯誤輸出結(jié)果同上finally。 // err finally // new finally。
當我修改try的語句:
function trycatch () { try{ // } catch(e){ console.log('err finally'); return console.log('new finally') }}trycatch ()// 空(viod)// 空(viod)
結(jié)果就輸出都為空。// 空(viod)。因為try沒有扔出錯誤,所以catch沒有捕獲到異常,故輸出結(jié)果就為空。
那么我們再看看下面這個案例,通過下面的例子,可能會讓你更加地了解try catch語句的異常處理。
try{ try{ throw new Error('open'); } catch(e){ console.info(e.message); throw e } finally{ console.log('finally'); }}catch(e){ console.log('op',e.message);}// open// finally// op open
當我們在try可能引發(fā)錯誤的代碼塊內(nèi)嵌套try catch,通過嵌套的代碼塊try內(nèi)扔一條可能出現(xiàn)錯誤的語句 throw new Error('open');,緊接著嵌套的try將錯誤傳遞給嵌套的catch處理,最終通過嵌套的finally運行過后,我們看到最后一條結(jié)果// op open,其實嵌套的catch捕獲的錯誤信息扔給最外層catch捕獲的。// op open
也就是說:任何給定的異常只會被離它最近的封閉catch塊捕獲一次。
當然,在“內(nèi)部”塊拋出的任何新異常(因為catch塊里的代碼也可以拋出異常),都將會被“外部”塊所捕獲。
以上就是本文的全部內(nèi)容,希望對大家學習javascript程序設計有所幫助。