Last active
July 30, 2019 02:05
-
-
Save kodaitakahashi/f106a6fa20da99c7e014d3cbf41682af to your computer and use it in GitHub Desktop.
抽象メソッドのthrowsで例外について定義されている場合、実装メソッドの書き方や挙動
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// abstractClass.java | |
import java.io.IOException; | |
public abstract class AbstractClass { | |
public abstract void throwIOException() throws IOException; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// main.java | |
// 注意 このコードはそのままコピペをするとエラーがでます。 | |
// 確かめる場合はオーバーライドされているメソッドを一つ選んで、他はコメントアウトして実行してください。 | |
import java.io.FileNotFoundException; | |
import java.io.IOException; | |
public class Main extends AbstractClass { | |
// 抽象メソッドで定義した例外クラスをthrowsで定義しなくても実装が可能 | |
// しかし、IOExceptionの例外をメソッドの呼び出し元に向けて起こすことができない | |
@Override | |
public void throwIOException() { | |
} | |
// IOExceptionの例外をメソッドの呼び出し元に向けて起こするためには、throwsを記述する必要がある | |
@Override | |
public void throwIOException() throws IOException { | |
throw new IOException("例外を発生させることができるよ"); | |
} | |
/// 抽象メソッドで定義した例外クラスじゃなく別の例外クラスでも実装が可能 | |
@Override | |
public void throwIOException() throws FileNotFoundException { | |
throw new FileNotFoundException(); | |
} | |
// 以下のthrowIOExceptionはコンパイルエラー | |
@Override | |
public void throwIOException() throws Exception { | |
throw new Exception(); | |
} | |
public static void main(String[] args) { | |
Main main = new Main(); | |
try { | |
main.throwIOException(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment