try{
정상적으로 처리되어야할 코드
런타임에서 에러가 발생하여 에외가 발생하거나,
throw 문을 통해 예외를 직접 발생시킬수 있다.
}catch(e){
예외 발생시 실행될 코드
예외와 관련된 정보를 e 변수를 통해 참조
예외를 처리 or 무시할수 있고,
throw문을 통해 예외를 다시 발생시킬수 있습니다.
}finally{
try, catch 실행 완료후 무조건 실행이 필요한 코드
}
var x = 5; var result; try{ result = x * y; document.writeln(result); } catch(e){ document.writeln(e); }finally{ document.writeln('ok'); } /* result : ReferenceError: y is not defined ok */ try{ result = x / 0; document.writeln(result); throw new Error('0으로 나눌 수 없습니다.'); } catch(e){ document.writeln(e); document.writeln('
'); }finally{ document.writeln('ok'); document.writeln('
'); } /* result : 5 Error: 0으로 나눌 수 없습니다. ok */ try{ var calculator; calculator = calculator || {add : function(op1, op2){ return op1 + op2; }}; calculator && document.write(calculator.add(2,3)); calculator && document.write(calculator.sub(2,3)); }catch(e){ document.write(e); } /* result : 5 TypeError: calculator.subtract is not a function */