예외처리 throw, try, catch

var add = function(a, b){
  if(typeof a !== 'number' || typeof b !== 'number'){
    throw{
      name: 'TypeError',
      message: 'add needs numbers'
    }
  }
  return a + b;
};

var try_it = function(){
  try{
    add("seven");
  } catch(e){
    console.log(e.name + ": " + e.message);
  }
}
try_it();

throw 에서 예외발생시 표시할 속성들을 만들어 놓는다.
try 블록 안에서 예외가 발생하면 catch 로 던져진다.
catch 블록 안에서 throw 객체의 속성들을 이용해서 처리할 수 있다.

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다