0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

異常終了について

0
Posted at

異常終了(return 1; などを使って終了)すると、プログラムは 正常に動作しなかったことをシステムに伝える ことになります。

✅ 異常終了の影響
プログラムの途中で終了する

return 1; を実行した時点で、それ以降のコードは実行されずにプログラムが終わる。

例えば、ファイルを開けなかった場合、異常終了を使うとその後の処理(ファイルの読み込みや出力)は一切実行されない。

シェルやスクリプトから異常終了を検知できる

Cプログラムが異常終了すると、終了コード 1(または他の値)をシェルに返す。

シェルスクリプトやバッチファイルなどで エラーチェック をする際に使える。

sh
./program
echo $?
$? は直前のコマンドの終了コードを取得するもので、異常終了なら 1 が返る。

エラーメッセージを表示できる

perror() を使えば、異常終了時に適切な エラーメッセージ を表示できる。

ユーザーに何が問題だったのか伝えるための デバッグ情報 にもなる。

✅ 異常終了の実例
例えば、ファイルが存在しない場合に 異常終了をさせる 場合:

c
#include

int main() {
FILE *file = fopen("missing.txt", "r");
if (file == NULL) {
perror("ファイルを開けませんでした");
return 1; // 異常終了
}

printf("ファイルを正常に開きました!\n");
fclose(file);

return 0;

}
missing.txt が 存在しない場合 → perror("ファイルを開けませんでした"); のメッセージとともに return 1; により異常終了

存在する場合 → printf("ファイルを正常に開きました!\n"); が実行される

✅ まとめ
🔹 異常終了をすると、プログラムの途中で終了する 🔹 シェルやスクリプトは異常終了を検知できる(エラー処理に便利) 🔹 適切なエラーメッセージを表示できる(デバッグに役立つ)

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?