LoginSignup
0
1

More than 3 years have passed since last update.

【JavaScript】例外処理try~catch文の使い方

Last updated at Posted at 2020-05-07

【JavaScript】例外処理try~catch文の使い方

try~catch文はエラー発生箇所に仕掛け、エラーを出す条件が整ったら別の処理を実行するための構文。
if~else文と似ている。


        let arr = ["1, 2, 3, 4, 5"];
        console.log(aar.includes(1,0));//arrを呼び出すべきところをarrに指定
        console.log("end");

この場合、Uncaught ReferenceError: aar is not defined が表示され、
3行目のconsole.log("end");は実行されない。

try~catch文を使ったエラー回避例

1.try{}でエラーが出る範囲を囲む
2.catch (e)を間に入れる
 "e"は引数、どの文字列でも良い
 慣習的にcatch (e) とされることが多い


        let arr = ["1, 2, 3, 4, 5"];
        try{
            console.log(aar.includes(1,0));
        } catch (e) {
            console.log(e);//エラー内容を表示。
        }
        console.log("end");

Uncaught ReferenceError: aar is not defined が表示されつつも、最終処理console.log("end");のおかげで
"end"が表示される。

RPGツクールの例

RPGツクールMVではセーブやロード実行時にtry~catch文が確認できる。
rpg_manager.js 337行目の箇所


    DataManager.saveGame = function(savefileId) {
        try {
            StorageManager.backup(savefileId);
            return this.saveGameWithoutRescue(savefileId);
        } catch (e) {
            console.error(e);
            try {
                StorageManager.remove(savefileId);
                StorageManager.restoreBackup(savefileId);
            } catch (e2) {
            }
            return false;
        }
    };

これは
・セーブに成功したら、セーブファイルのIDと共にsaveGameWithoutRescue(=救済処理を必要としないセーブ処理に遷移
・セーブに失敗したら、StorageManager.remove、StorageManager.restoreBackupといった別処理に遷移ということなのでしょう。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1