例外処理の基本
try {
処理
}
catch { // 例外ハンドラ
例外処理
}
finally { // finallyブロック
常に処理
}
@test
public void testYetAnother {
Logger l = Logger.getLohgger(Employee.class.getName());
// Employee employee1 = new Employee();
try {
Employee employee1 = null;
employee1.setName("J Smith);
Employee employee2 = new Employee();
employee2.setName("J Smith");
l.info("Q: employee == employee2? A: " + (employee1 == employee2));
l.info("Q: employee1.equals(employee2)? A: " + employee1.equals(employee2));
}
catch (Exception e) {
1.severe("Caught exception: " + e.getMessage));
}
finally {
// Always executes
}
}
例外の階層
複数のcatchブロック
@Test
public void testException() {
logger l = Logger.getLogger(Employee.class.geName());
File file = new File("file.txt");
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader( new FileReader(file));
String line = bufferedReader.readLine();
while(line != null) {
// Read the file
}
}
catch (FileNotFoundException e) {
l.severe(e.getMassage());
}
catch (IOException e) {
l.severe(e.getMessage());
}
catch (Exception e) {
l.severe(e.getMessage());
}
finally {
// Close the readeer
}
}
try-with-resourcesブロック
リソースを自動的に解放したい場合、tryの引数にリソースを記述する
@Test
public void testException() {
logger l = Logger.getLogger(Employee.class.geName());
File file = new File("file.txt");
BufferedReader bufferedReader = null;
try (bufferedReader = new BufferedReader( new FileReader(file))) {
bufferedReader = new BufferedReader( new FileReader(file));
String line = bufferedReader.readLine();
while(line != null) {
// Read the file
}
}
catch (FileNotFoundException e) {
l.severe(e.getMassage());
}
catch (IOException e) {
l.severe(e.getMessage());
}
catch (Exception e) {
l.severe(e.getMessage());
}
finally {
// Close the readeer
}
}
throwsとthrow
static void check(int sw) throws Exceptions {
switch(sw) {
case 1: throw new Exception("Exception");
case 2: throw new RunTimeException("RunTimeException) ;
}