戻る

try ... catchについて
try catchのエラーについて

Error
1.構文エラ(文法エラー)
プログラムの実装をした際に作ってしまったエラーです。
キーワードのタイプミスやカッコの閉じる個数の過不足などがあります。
2.論理エラー
プログラムは実行できても仕様にそぐわない結果を実行してしまう結果のプログラムです。
原因としては変数に設定する値や条件のミスや条件分岐のタイミングによるエラーがあります。
エラーが発生するとErrorオブジェクトが生成します。
(1) name
エラーの種類を表す文字列です。
(例)
TypeError
ReferenceError
(2) message
詳細なエラーメッセージです。
(例)
"Cannot read property 'xxx' of undefined".
(3) stack
エラーが発生した場所を示すスタックトレースを表示します。

copy
try {
  //エラーが発生すると仮定します
  let result = test();
} catch (error) {
  //エラーが発生した場合の処理
  console.error(error.name);//(例)TypeError
  console.error(error.message);//(例)Cannot read property 'xxx' of undefined.
  console.error(error.stack);//(例)スタックトレース
}
カスタムエラーの作成
Errorオブジェクトを継承することで独自のエラーを作成することができます。
copy
class ValidationError extends Error
{
	constructor(message, value)
	{
		super(message);
		this.name = 'ValidationError';
		this.field = field;
	}
}

let range = 0;
...
try
{
	//バリデーションエラーを発生させる
	throw new ValidationError('データ範囲外', range);
} catch (error) {
	if (error instanceof ValidationError)
	{
		console.error(error.name);//(例)ValidationError
		console.error(error.message);//(例)データ範囲外
		console.error(error.value);//(例)rangeの値
	}
}
ReferenceError
参照先が不明な場合に起きるエラーです。
ReferenceErrorが発生する主な原因
(1)変数の未定義
変数をletやconstなどで宣言せずに使用しようとしたケース
copy
function test1() 
{
  // 'result' は宣言されていません
  console.log(result);//ReferenceError: result is not defined
}
test1();
スコープ外の変数を参照しようとしたケース
(例)
関数内でローカル変数にアクセスしようとしたケース
undefined や null の変数のプロパティにアクセスしようとした場合。
copy
let data1 = 1;
function test2() {
    console.log(data1);//1(スコープ内)
    console.log(data2);//ReferenceError: data2 is not defined (スコープ外)
}
test2();
(2)スペルミス
変数名や関数名をタイプミスした場合。
(3)非同期処理の問題
非同期処理
(例)
setTimeoutやfetchの中で、まだ定義されていない変数を参照しようとしたケース。
copy
//undefined のオブジェクトのプロパティにアクセス
let obj = undefined;
try 
{
    console.log(obj.prop);//ReferenceError: Cannot read properties of undefined (reading 'prop')
}catch (e){
    console.log(e);
}
SyntaxError
コードの構文(文法)が間違っている場合に発生するエラーです。
(例)
括弧や引用符の閉じ忘れ
文の区切りミス:セミコロン「;」の実装し忘れ
配列の要素エラー:要素数を超えた位置にアクセスしようとした場合
copy
function test()
{
	const ary=[];
	for(i=0;i<3;i++)
	{
		ary[i]=i+1;
	}
	//下記の部分では要素不足のためエラーが発生します
	if(ary[3]==3)
	{
		...
	}	
}
test();
TypeError
オブジェクトの仕様と異なる設定や実行をしたときに発生するエラーです。
(例)
型が一致しない
関数の引数の型が合わない
プロパティへの不正なアクセス
例えば、存在しないオブジェクトのプロパティにアクセスしようとしたり、
nullやundefinedのオブジェクトにプロパティを設定しようとしたケース
copy
const num = "100";
const sum = num + 10;//TypeError: 文字列と数値の加算は型エラー

const obj = null;
obj.property = "aaa";//TypeError: nullオブジェクトのプロパティにアクセス
RangeError
数値が有効な範囲外で使用された場合に発生するエラーです。

const ary = new Array(-1); //RangeError: Invalid array length
配列の長さは0以上の整数の必要があるため。

const invalidDate = new Date('2026-12-32'); // RangeError: Invalid time value
存在しない日付 (12月32日) を指定すると、RangeErrorが発生します。

URIError
URI(Uniform Resource Identifier)を扱う関数が不正な引数で呼び出された場合に発生するエラーです。
(例)
encodeURI()やdecodeURI()`で不正なURIを処理しようとした場合
encodeURI()は、URIの予約文字をエスケープせずにエンコードしようとした場合
(例)
「;」「/」「?」「:」「@」「&」「=」「+」「$」「,」「#」
decodeURI()は、不正なエスケープシーケンスを含むURIをデコードしようとした場合
copy
try 
{
  decodeURI('%'); // %は単独では不正なエンコード
} catch (e) {
  if (e instanceof URIError) {
    console.log("URIErrorが発生しました:", e.message);
  }
}

EvalError
セキュリティ上の理由から使用は推奨されていません。
古いバージョンのJavaScriptとの互換性で使われます。
SyntaxErrorやその他のエラーで処理のため残されています。

EvalErrorの役割
eval()関数の呼び出しで問題が発生した場合にEvalErrorがスローされていました。
[現在]
主にSyntaxErrorや他のエラーによって処理されます。

eval()のセキュリティリスク
外部から入力された文字列をeval()で実行すると、意図しないコードが実行される可能性があり、セキュリティ上のリスクがあります。

[代替手段]
下記を実装することで対応することが推奨されています。
JSON.parse()
new Function()

(例)
copy
try {
	eval("1 + 1"); // 通常は問題ない
	eval("throw new Error('test')"); // エラーが発生
} catch (e) {
	if (e instanceof EvalError) {
		console.log("EvalErrorが発生しました。");
	} else {
		console.log("EvalError以外のエラーが発生しました。", e);
	}
}


戻る
back

about try ... catch
about try ... catch error

Error
1. Syntax error (grammar error)
These are errors that were made when implementing the program.
These include typos in keywords and too many or too few closing parentheses.
2. Logical Error
Even if the program can be executed, it will end up executing results that do not match the specifications.
The causes of this include errors in the values ​​or conditions set for variables, or errors due to the timing of conditional branching.
When an error occurs, an Error object is created.
(1) name
A string that indicates the type of error.
(Example)
TypeError
ReferenceError
(2) message
A detailed error message.
(Example)
"Cannot read property 'xxx' of undefined".
(3) stack
Displays a stack trace showing where the error occurred.

copy
try {
  //Assuming you get an error
  let result = test();
} catch (error) {
  //What to do if an error occurs
  console.error(error.name);//(例)TypeError
  console.error(error.message);//(例)Cannot read property 'xxx' of undefined.
  console.error(error.stack);//(例)Stack trace
}
Creating custom errors
You can create your own errors by inheriting the Error object.
copy
class ValidationError extends Error
{
	constructor(message, value)
	{
		super(message);
		this.name = 'ValidationError';
		this.field = field;
	}
}

let range = 0;
...
try
{
	//Raising Validation Errors
	throw new ValidationError('Data out of range', range);
} catch (error) {
	if (error instanceof ValidationError)
	{
		console.error(error.name);//ex.)ValidationError
		console.error(error.message);//ex.)Data out of range
		console.error(error.value);//ex.)range value
	}
}
ReferenceError
This error occurs when the reference is unknown.
Main causes of ReferenceError
(1) Undefined variable
An attempt was made to use a variable without declaring it using let or const etc.copy
function test1() 
{
  //'result' is undeclared
  console.log(result);//ReferenceError: result is not defined
}
test1();
Cases where an attempt is made to reference a variable outside of its scope
(Example)
Case where an attempt is made to access a local variable within a function
When an attempt is made to access a property of an undefined or null variable.
copy
let data1 = 1;
function test2() {
    console.log(data1);//1(In scope)
    console.log(data2);//ReferenceError: data2 is not defined (Out of scope)
}
test2();
(2) Spelling mistakes
When you make a typo in a variable or function name.
(3) Asynchronous processing issues
Asynchronous processing
(Example)
When trying to reference a variable that has not yet been defined in setTimeout or fetch. 
copy
//Accessing properties of an undefined object
let obj = undefined;
try 
{
    console.log(obj.prop);//ReferenceError: Cannot read properties of undefined (reading 'prop')
}catch (e){
    console.log(e);
}
SyntaxError
This error occurs when the code syntax (grammar) is incorrect.
(Example)
Forgetting to close parentheses or quotation marks
Mis-delimiting a statement: Forgetting to implement a semicolon ";"
Array element error: When attempting to access a position beyond the number of elements
copy
function test()
{
	const ary=[];
	for(i=0;i<3;i++)
	{
		ary[i]=i+1;
	}
	//An error occurs in the following part due to a lack of elements.
	if(ary[3]==3)
	{
		...
	}	
}
test();
TypeError
This error occurs when you configure or execute something that does not match the object's specifications.
(Example)
Type mismatch
Function argument types do not match
Invalid access to property
For example, when you try to access a property of a non-existent object, or
when you try to set a property on a null or undefined object
copy
const num = "100";
const sum = num + 10;//TypeError: Adding a string and a number causes a type error

const obj = null;
obj.property = "aaa";//TypeError: Accessing properties of a null object
RangeError
This error occurs when a number is used outside the valid range.

const ary = new Array(-1); //RangeError: Invalid array length
The length of the array must be an integer greater than or equal to 0.

const invalidDate = new Date('2026-12-32'); // RangeError: Invalid time value
If you specify a date that does not exist (December 32nd), a RangeError will occur.



back



著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームペーよびアプリ利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。