Core JavaScript 1.5 Guide:Exception Handling Statements:throw Statement
出典: MDC
[編集] throw 文
throw 文は例外を投げるために使用します。例外を投げるときは、投げたい値からなる式を指定してください。
throw expression;
特定の型の式だけではなく、あらゆる式を投げることができます。以下のコードはあらゆる型からなる例外を投げます。
throw "Error2";
throw 42;
throw true;
throw {toString: function() { return "I'm an object!"; } };
注意:例外を投げる際にオブジェクトを指定することができます。すると、
catch ブロックでそのオブジェクトのプロパティを参照できるようになります。次の例では UserException という種類の myUserException というオブジェクトを作ります。また、このオブジェクトを throw 文で使用します。// UserException という種類のオブジェクトを作成
function UserException (message)
{
this.message=message;
this.name="UserException";
}
// 文字列として使用されるとき(例:エラーコンソール上)に
// 例外を整形する
UserException.prototype.toString = function ()
{
return this.name + ': "' + this.message + '"';
}
// そのオブジェクトの種類のインスタンスを作成し、それを投げる
throw new UserException("Value too high");