PHPで例外処理(try-catch()) チートシート

想定した例外と想定していない例外を分けたい

作成日:2025-11-18, 更新日:2025-11-18

基本

・例外は特別な理由がないなら「RuntimeException」を使ってthrowする
・指定無き例外(PHPエラーなど)は、「Exception(PHP7以上ならThrowableが望ましい。Exceptionより幅広く「Error(Fatal Errorなど)」も捕捉)」がcatchしてくれる

try {
	if ( 条件(データが重複...など) ) {
		throw new \LogicException(〇〇〇);
	}

	if ( 条件(登録や取得が想定外に失敗...など) ) {
		throw new \RuntimeException(〇〇〇);
	}
}
catch (\LogicException $e) {
	var_dump([
		'概要' => 'ロジックエラー' . $e->getMessage(),
		'発生個所' => 'line=' . $e->getLine() . ' on ' . $e->getFile(),
	]);
}
catch (\RuntimeException $e) {
	var_dump([
		'概要' => '想定通りの例外' . $e->getMessage(),
		'発生個所' => 'line=' . $e->getLine() . ' on ' . $e->getFile(),
	]);
}
catch (\Throwable $e) {
	var_dump([
		'概要' => '想定外の例外' . $e->getMessage(),
		'発生個所' => 'line=' . $e->getLine() . ' on ' . $e->getFile(),
	]);
}

laravel + DB(ロールバック関連)

try {
	\DB::beginTransaction();

	if ( 条件(データが重複...など) ) {
		throw new \LogicException(〇〇〇);
	}

	if ( 条件(登録や取得が想定外に失敗...など) ) {
		throw new \RuntimeException(〇〇〇);
	}

	// ==================
	\DB::commit();
}
catch (\LogicException $e) {
	\DB::rollBack();
	var_dump([
		'概要' => 'ロジックエラー' . $e->getMessage(),
		'発生個所' => 'line=' . $e->getLine() . ' on ' . $e->getFile(),
	]);
}
catch (\RuntimeException $e) {
	\DB::rollBack();
	var_dump([
		'概要' => '想定通りの例外' . $e->getMessage(),
		'発生個所' => 'line=' . $e->getLine() . ' on ' . $e->getFile(),
	]);
}
catch (\Throwable $e) {
	\DB::rollBack();
	var_dump([
		'概要' => '想定外の例外' . $e->getMessage(),
		'発生個所' => 'line=' . $e->getLine() . ' on ' . $e->getFile(),
	]);
}

関連項目