JS中的異常捕獲

JS中的異常捕獲:
(1) try …catch
(2) try…finally
(3) try…catch…finally
用法主要有以上三種,try語句必須搭配catch語句或者finally語句或者三個在一起使用。
作用:針對try塊中的語句塊可能拋出的異常進行處理。

  1. try…catch
	try {
		throw new Error('出錯啦!')
		console.log(1)
	}catch(e) {
		console.log(e)   //Error: 出錯啦! at <anonymous>:2:8
	}

以上代碼不會打印出‘1’,因爲try塊中的語句中拋出異常的時候,會立即轉到相應的catch語句(只是針對這裏只有catch塊的情況),並且生成一個臨時變量(這裏是e),以便在catch塊中進行訪問。
2. try…finally

//拋出錯誤的情況
	try {
		throw new Error('出錯啦!')
		console.log(1)
	}finally{
		console.log(2) //打印出2  並報錯:VM202:2 Uncaught Error: 出錯啦!at <anonymous>:2:9
	}
//沒有拋出錯誤的情況
	try {
		console.log(1) //打印出1
	}finally{
		console.log(2) //打印出2
	}

以上代碼表明,無論是否出錯,都會執行finally語句。
3. try…catch…finally

	try {
		throw new Error('出錯啦!')
		console.log(1)
	}catch(e) {
		console.log(e) //Error: 出錯啦!at <anonymous>:2:9VM215:7
	}finally{
		console.log(2) //打印出 2
	}
  1. 嵌套try…catch…finally
//內層存在catch塊
try{
	try {
		throw new Error('出錯啦!')
		console.log(1)
	}catch(e) {
		console.log(e) //Error: 出錯啦!at <anonymous>:2:9VM215:7
	}finally{
		console.log(2) //打印出 2
	}
}catch(e) {
	console.log(e)
}
//內層不存在catch塊
try{
	try {
		throw new Error('出錯啦!')
		console.log(1)
	}finally{
		console.log(2) //打印出 2
	}
	console.log(3)
}catch(e) {
	console.log(e) //Error: 出錯啦!at <anonymous>:3:9
}

以上代碼表明:如果內層存在catch塊,那麼try塊中拋出的錯誤會被內層catch塊捕獲,如果內層不存在catch塊,那麼try塊中拋出的錯誤會被外層catch塊捕獲,且try塊後面的代碼不會執行,因此這裏不會打印出‘3’。
總結:
(1)如果try塊中拋出錯誤,那麼try塊中錯誤拋出語句後面的其他語句均不會執行;
(2)不管try塊中是否拋出錯誤,finally塊語句一定會被執行;
(3)內層try塊拋出的錯誤會被對應內層的catch塊捕獲,如果不存在對應的內層catch塊,那麼會被拋到上一層,被上一層的catch塊捕獲,如果還沒有被捕獲,那麼繼續拋到上一層,直到最外層。

以上。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章