node——try-catch與異步操作


 //try-catch,用於捕獲異常
 //try-catch在node中只能捕獲同步的異常,不能捕獲異步異常
 var fs=require('fs');
 /*fs.writeFile('./abc.txt','大家早上好!','utf-8',function(err){
     if(err){
         console.log('出錯了');
         throw err; // 只要拋出錯誤,后面的代碼就不會執行
     }
     console.log('ok');
 })*/
//這個時候不會報錯,並且也沒有寫入,所以異步操作,try-catch無法處理異常,需要使用錯誤號
 try{
     fs.writeFile('./yyy/abc.txt','大家早上好!','utf-8',function(err){
 
     console.log('ok');
 }) 
 }catch(e){
     console.log('出錯了'+e);
 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM