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?

[TS] 例外処理ブロックのスコープについて

Posted at

はじめに

PythonとTypeScriptにおいての、
例外処理ブロックのスコープの違いについて
自分の中で整理をつけるためにまとめました。

Python

Pythonの場合、tryブロック内で宣言した変数は
exceptブロック内・例外処理ブロック外でも参照可能。

try:
	user_name = "Taro"
	raise Exception("例外が発生")
except Exception as e:
	print(f"except内 : {user_name}")
	print(e)

print(f"try~exceptの外 : {user_name}")

# except内 : Taro
# 例外が発生
# try~exceptの外 : Taro

TypeScript (const、let)

TypeScriptの場合、tryブロック内で宣言した変数は
catchブロック内・例外処理ブロック外では参照不可。
下記のサンプルでは、letを利用しているがconstでも同じである。

try {
    let userName: string = "Taro"
    throw new Error("例外が発生")
} catch (error) {
    console.log(`catch内 : ${userName}`)
    console.log(error.name)
}

console.log(`try~catchの外 : ${userName}`)

// error TS2304: Cannot find name 'userName'.
// error TS2304: Cannot find name 'userName'.

対処法

例外処理ブロックの外で、変数の宣言を行うことで
catchブロック内・例外処理ブロック外でも参照可能になる。

let userName: string;

try {
    userName = "Taro"
    throw new Error("例外が発生")
} catch (error) {
    console.log(`catch内 : ${userName}`)
    console.log(error.name)
}

console.log(`try~catchの外 : ${userName}`)

// catch内 : Taro
// Error
// try~catchの外 : Taro

あとがき

Pythonの文法ルールってゆるい

参考

0
0
1

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?