JavaScriptにおけるエラー処理
この記事ではJavaScriptにおけるエラー処理について説明します。
YouTube Video
JavaScriptにおけるエラー処理
JavaScriptにおけるエラー処理は、プログラムが予期しない問題に遭遇した場合に、エラーをキャッチして適切に対処するために重要な機能です。主に、try...catch
構文を使ってエラーをキャッチし、処理する方法が一般的です。また、Promiseや非同期処理を行う場合は、async/await
やPromise.prototype.catch
を用いたエラー処理もあります。
try...catch
構文
try...catch
は、コードブロック内でエラーが発生した際に、そのエラーをキャッチして処理するために使われます。
1try {
2 // Code that may throw an error
3 let result = riskyFunction();
4 console.log(result);
5} catch (error) {
6 // Catch and handle the error
7 console.error("An error occurred:", error.message);
8} finally {
9 // Code that will always execute
10 console.log("Error handling has completed.");
11}
try
ブロック内でエラーが発生すると、プログラムの実行が中断され、catch
ブロックが実行されます。finally
ブロックはエラーの有無に関係なく必ず実行されます。リソースの解放や終了処理などに便利です。
エラーのスロー (throw
)
JavaScriptでは、throw
キーワードを使って明示的にエラーを発生させることができます。独自のエラーメッセージやカスタムエラーをスローする場合に使われます。
1function checkAge(age) {
2 if (age < 18) {
3 throw new Error("You are under 18 years old.");
4 }
5 return "Age verification completed.";
6}
7
8try {
9 let result = checkAge(15);
10 console.log(result);
11} catch (error) {
12 console.error(error.message); // Displays "You are under 18 years old."
13}
非同期処理のエラー処理 (Promise
と async/await
)
非同期処理を行う場合、エラー処理は少し異なります。Promiseを使用する場合は、catch
メソッドでエラーをキャッチします。
1let promise = new Promise((resolve, reject) => {
2 // Asynchronous operation
3 setTimeout(() => reject(new Error("An issue has occurred!")), 1000);
4});
5
6promise
7 .then(result => console.log(result))
8 .catch(error => console.error(error.message)); // Displays "An issue has occurred!"
async/await
を使用して非同期処理を行う場合も、try...catch
を使ってエラーを処理できます。
1async function fetchData() {
2 try {
3 let response = await fetch('https://api.example.com/data');
4 let data = await response.json();
5 console.log(data);
6 } catch (error) {
7 console.error("An error occurred while fetching data:", error.message);
8 }
9}
10
11fetchData();
まとめ
try...catch
構文で同期エラーをキャッチできます。throw
で独自のエラーをスローすることができます。- 非同期処理のエラーは、
Promise
のcatch
メソッドやasync/await
とtry...catch
で処理することができます。
これらの方法を活用して、エラーが発生してもプログラムが適切に動作するようにできます。
Error
Error
クラスは、エラー処理に使われます。エラーを作成し、エラーメッセージやスタックトレースを提供する機能があります。
1try {
2 throw new Error("Something went wrong");
3} catch (e) {
4 console.log(e.message); // Something went wrong
5}
基本的な使い方
Error
オブジェクトは、エラーが発生した際に明示的に生成することができます。new Error()
を使ってインスタンスを作成し、エラーメッセージを渡します。
1const error = new Error("Something went wrong");
2console.log(error.message); // "Something went wrong"
3console.log(error.name); // "Error"
4
5// Stack trace (information about where the error occurred)
6console.log(error.stack);
Error
オブジェクトのプロパティ
Error
オブジェクトには以下のプロパティがあります。
message
: エラーメッセージです。name
: エラーの名前で、デフォルトは"Error"
です。stack
: エラーが発生した場所を含むスタックトレースで、デバッグに役立ちます。
throw
によるエラーのスロー
JavaScriptでは、throw
キーワードを使ってエラーを投げることができます。これは、特定の状況で処理を中断し、エラーハンドラーに制御を渡すために使用されます。
1function doSomething() {
2 throw new Error("This function is not yet implemented");
3}
4
5try {
6 doSomething();
7} catch (e) {
8 console.error(e.message); // "This function is not yet implemented"
9}
throw
で投げられたエラーは、try...catch
構文を使ってキャッチすることができます。
カスタムエラーの作成
JavaScriptでは、Error
クラスを継承して独自のカスタムエラーを作成することが可能です。これにより、特定の状況に対応したエラーを作成することができます。
1class CustomError extends Error {
2 constructor(message) {
3 super(message); // Call the parent class constructor
4 this.name = "CustomError"; // Set the error name
5 }
6}
7
8try {
9 throw new CustomError("A custom error has occurred");
10} catch (e) {
11 console.error(e.name); // "CustomError"
12 console.error(e.message); // "A custom error has occurred"
13}
組み込みのエラークラス
JavaScriptには、Error
クラスを継承した複数の組み込みエラークラスがあります。これらは特定のエラーを表現するために使用されます。
ReferenceError
: 存在しない変数を参照した場合に発生します。TypeError
: 値の型が期待される型と異なる場合に発生します。RangeError
: 数値が許容範囲を超えた場合に発生します。SyntaxError
: 文法的に正しくないコードが実行された場合に発生します。EvalError
:eval()
関数の使用に関するエラーです。現在はほとんど使われません。URIError
: 無効なURI(エンコードやデコードのエラー)が使用された場合に発生します。
例: ReferenceError
以下は、ReferenceError
の例です。
1try {
2 console.log(undefinedVariable); // Undefined variable
3} catch (e) {
4 console.error(e.name); // "ReferenceError"
5 console.error(e.message); // "undefinedVariable is not defined"
6}
例: TypeError
以下は、TypeError
の例です。
1try {
2 null.f(); // Attempting to call a function on null
3} catch (e) {
4 console.error(e.name); // "TypeError"
5 console.error(e.message); // "Cannot read properties of null (reading 'f')"
6}
finally
ブロック
try...catch
構文では、エラーが発生しても発生しなくても、必ず実行したい処理がある場合、finally
ブロックを使用します。
1try {
2 throw new Error("An issue has occurred");
3} catch (e) {
4 console.error(e.message); // "An issue has occurred"
5} finally {
6 console.log("Performing cleanup");
7}
この例では、エラーがスローされても、finally
ブロック内の処理は実行されます。
例外処理の利点
エラーハンドリングを正しく実装することで、予期しない動作が起こった際に、アプリケーションがクラッシュするのを防ぐことができます。try...catch
構文やエラーオブジェクトを適切に使用することで、より堅牢なコードを書くことができます。
1function divide(a, b) {
2 if (b === 0) {
3 throw new Error("Cannot divide by zero");
4 }
5 return a / b;
6}
7
8try {
9 console.log(divide(4, 0)); // An error will occur
10} catch (e) {
11 console.error(e.message); // "Cannot divide by zero"
12}
まとめ
Error
クラスは、エラーの原因を表現し、エラーハンドリングを行うために使用されます。try...catch...finally
構文を使ってエラー処理を行い、アプリケーションの予期しない終了を防ぎます。Error
クラスを拡張してカスタムエラーを作成することも可能です。- 組み込みのエラークラス(
TypeError
,ReferenceError
など)を使って、さまざまな種類のエラーを処理できます。
YouTubeチャンネルでは、Visual Studio Codeを用いて上記の記事を見ながら確認できます。 ぜひYouTubeチャンネルもご覧ください。