Skip to content

Instantly share code, notes, and snippets.

@kodaitakahashi
Last active July 30, 2019 02:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kodaitakahashi/f106a6fa20da99c7e014d3cbf41682af to your computer and use it in GitHub Desktop.
Save kodaitakahashi/f106a6fa20da99c7e014d3cbf41682af to your computer and use it in GitHub Desktop.
抽象メソッドのthrowsで例外について定義されている場合、実装メソッドの書き方や挙動
// abstractClass.java
import java.io.IOException;
public abstract class AbstractClass {
public abstract void throwIOException() throws IOException;
}
// 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