Core > 例外

JavaScriptの例外のまとめ。

by s_hiroshi

JavaScript

// 例外
// https://developer.mozilla.org/ja/Core_JavaScript_1.5_Reference/Global_Objects/Error
// 1. 組み込みの例外
// 2. throw文で例外を投げる
//    2-1 組み込み例外
//    2-2 カスタム例外

// my z; 単なる構文エラー JavaScriptはmyという構文はない。

// 1. 組み込みの例外
// EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError
try {
    console.log(x); // ReferenceError
} catch (e) {
    console.log('name: ' + e.name + ',' + ' message: ' + e.message + ', toString: ' + e.toString());
}


// 例外は発生しない例
var y;
try {
    console.log(y); // undefined undefinedは例外ではない
} catch (e) {
    console.log('name: ' + e.name + ',' + ' message: ' + e.message + ', toString: ' + e.toString());
}
// undefinedの場合に例外を強制的に発生させる
try {
    if (typeof y === 'undefined') {
        throw new Error('undefined Error');
    }
} catch (e) {
     console.log('name: ' + e.name + ',' + ' message: ' + e.message + ', toString: ' + e.toString());
}

var o = {};
try {
    o = parseInt(o);
    console.log(o); // NaN
} catch (e) {
    console.log('name: ' + e.name + ',' + ' message: ' + e.message + ', toString: ' + e.toString());
}

try {
    var div = 10 / 0;
    console.log(div); // Infinity
} catch (e) {
    console.log('name: ' + e.name + ',' + ' message: ' + e.message + ', toString: ' + e.toString());
}
   



// 2-2 カスタムエラー
function CustomError(name, message) {
    this.name = name || 'CustomError';
    this.message = message || 'This is Custom Error';
    this.toString = function() {
        return 'This is CustomError';
    }
}
var pow = function(x) {
    if ((typeof x) !== 'number') {
        throw new CustomError('x is not number');
    } else {
        return Math.pow(x, 2);
    }
};


// try-catch
try {
    pow('a');
} catch (e) {
    console.log('name: ' + e.name + ',' + ' message: ' + e.message + ', toString: ' + e.toString());
}