LoginSignup
2
2

More than 5 years have passed since last update.

R言語のfinallyは先に実行される?【間違えがあったため追記】

Last updated at Posted at 2015-10-19

タイトル通りR言語でtryCatchをするときに、finallyは先に実行される?
Javaは最後に実行だったので驚いた。危うくバグを残すところだった。

R言語
tryCatch({
  rep("A",-1)  # ここで無理やりエラーを起こす
}, error = function(e) {
  print("エラー")
}, warning = function(e) {
  print("ワーニング")
}, finnaly = {
  print("ファイナリー")
})
実行結果
[1] "ファイナリー"
[1] "エラー"

本当に最初に実行される。「rep("A",-1)」よりも前に。
finallyは必ず実行する(最後とは言っていない)ということだろうか。

おまけ(java)

java
try{
    int a = 0 / 0;  // ゼロディバイドを起こす
} catch(ArithmeticException e) {
  System.out.println("エラー");
} finally {
  System.out.println("ファイナリー");
}
実行結果
エラー
ファイナリー

finallyは先に実行しても後で実行しても大丈夫なコード書きを心がけないとなと思いました。

追記

よく見たら「finally」ではなく「finnaly」と書いてました(汗

正しいfinally
tryCatch({
  rep("A",-1)  # ここで無理やりエラーを起こす
}, error = function(e) {
  print("エラー")
}, warning = function(e) {
  print("ワーニング")
}, finally = {
  print("ファイナリー")
})
実行結果
[1] "エラー"
[1] "ファイナリー"

R言語でも後で実行ということに。
これ、もしかしたら適当な変数だと先に実行されるのかな?

tryCatch({
  rep("A",-1)  # ここで無理やりエラーを起こす
}, error = function(e) {
  print("エラー")
}, warning = function(e) {
  print("ワーニング")
}, aaaa = {
  print("適当な変数")
}, finally = {
  print("ファイナリー")
})
実行結果
[1] "適当な変数"
[1] "エラー"
[1] "ファイナリー"

わああ、これはこれで気を付けなきゃ・・(汗

2
2
2

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