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?

More than 5 years have passed since last update.

[java] 例外をスローする

Posted at

例外処理はjavaの基本であるが、認識違いをしていたので備忘録として残す。

発生した問題

メソッドの呼び出し元に例外を投げたかったので、catchした例外をスローしようとすると、なぜかコンパイルエラーになっていた。

実装

例えばタイムアウトエラーを投げる場合は以下の通りである。

    public void foo(){
        try {
            fetch();
        } catch (SocketTimeoutException e) {
        }
    }

    public Integer fetch(){
        try {
            //Http通信
        } catch (SocketTimeoutException e) {
            throw e;//ここでコンパイルエラー
        }finally {
        }
        return number;
    }

認識違い

throwのほかに
thorws句というのがあるがこれはcatch文と同じ働きがあると思っていた。しかし実際それがあるメソッドは例外を投げる可能性がるメソッドという意味であった。

そこで例外をスローしているメソッドにthrows句を付け足すとコンパイルエラーが消え、foo()でキャッチできるようになった。

感想

基礎の基礎で躓くとは思わなかったが、今のうちに知れてよかった…

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?