![](/user_photo/48724_QpOGS.jpg)
3-й семестр / Лекции / 5 - Презентация 2
.pdf![](/html/48724/112/html_jjsHvZYcbh.e8Uz/htmlconvd-K7mIcs51x1.jpg)
Центр дистанционного обучения
Исключения
Path file = Paths.get(“file.txt”);
BufferedReader rdr = Files.newBufferedReader(file);
String line1 = rdr.readLine();
rdr.close(); // может быть не вызван, если в rdr.readLine() произойдет ошибка!
Открытые файлы всегда нужно закрывать!
online.mirea.ru
![](/html/48724/112/html_jjsHvZYcbh.e8Uz/htmlconvd-K7mIcs52x1.jpg)
Центр дистанционного обучения
Исключения
Path file = Paths.get(“file.txt”);
try (BufferedReader rdr = Files.newBufferedReader(file)) { String line1 = rdr.readLine();
}
В блоке try-with-resources rdr.close() вызывается автоматически!
online.mirea.ru
![](/html/48724/112/html_jjsHvZYcbh.e8Uz/htmlconvd-K7mIcs53x1.jpg)
Центр дистанционного обучения
Исключения
try (SomeResource res1 = ...;
OtherResource res2 = ...) {
// работа с res1 и res2; блок try может выбросить MyException
}
public class SomeResource implements AutoCloseable {
public void close() throws MyException {
// Вызывается при выходе из try-with-resources
}
}
online.mirea.ru
![](/html/48724/112/html_jjsHvZYcbh.e8Uz/htmlconvd-K7mIcs54x1.jpg)
Центр дистанционного обучения
Исключения
Блок try-with-resources может также иметь catch и finally:
Path file = Paths.get(“file.txt”);
try (BufferedReader rdr = Files.newBufferedReader(file)) {
String line1 = rdr.readLine();
}catch (NoSuchFileException ex) { System.out.println(“Файл не найден”);
}finally {
System.out.println(“Done”);
}
online.mirea.ru
![](/html/48724/112/html_jjsHvZYcbh.e8Uz/htmlconvd-K7mIcs55x1.jpg)
Центр дистанционного обучения
Исключения
Проблемы с checked exceptions:
public interface Runnable {
void run();
}
public class MyAction implements Runnable {
public void run() {
Files.write(Paths.get(“file.txt”), new byte[] {1});
}
}
online.mirea.ru
![](/html/48724/112/html_jjsHvZYcbh.e8Uz/htmlconvd-K7mIcs56x1.jpg)
Центр дистанционного обучения
Исключения
Проблемы с checked exceptions:
public class MyAction implements Runnable {
public void run() {
try {
Files.write(Paths.get(“file.txt”), new byte[] {1});
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
online.mirea.ru
![](/html/48724/112/html_jjsHvZYcbh.e8Uz/htmlconvd-K7mIcs57x1.jpg)
Центр дистанционного обучения
Исключения
Проблемы с checked exceptions:
public interface MyRunnable {
void run() throws ???;
}
•throws MyException – придется все другие исключения
(IOException, ...) заворачивать в него
•throws Exception – можно кидать любое исключение, но тогда все методы будут throws Exception
•Использовать только unchecked exceptions
online.mirea.ru