에러
런타임 에러
예외
예외처리(try-catch)
try{
int result= 10 / 0;
System.out.println(result);
}catch(ArithmeticException | IndexOutOfBoundsException e){ //에러 내용 복사해서 파라미터에 넣기, |로 이어주면 두개의 예외처리가 가능하다.
e.printStackTrace(); //어느 부분에서 에러가 발생했는지 콘솔창에 에러 메시지 나옴
}catch(NullPointerException e){
}catch(Exception e){ //모든 예외의 부모클래스인 Exception e를 추가(다형성)
e.printStackTrace();
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
test1();
}
private static void test1() {
test2();
}
private static void test2() {
// System.out.println(10/0); 여러개의 예외가 발생하면 가장 첫줄을 들어간다.
try {
new FileInputStream(""); //FileInputStream : 파일 경로 읽는 메서드, 파라미터에 경로 넣어줘야 함
// 에러 발생시키기 위해 파라미터에 ""넣음
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
finally
자동 자원반환
FileInputStream fis = null; //파일읽기 - 운영체제의 허락을 받아 파일을 연다.
try {
fis = new FileInputStream("d:/file.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//예외 발생 : try -> catch -> finally
//예외 미발생 : try -> finally
//자동 자원 반환(JDK1.7)
try(FileOutputStream fos = new FileOutputStream("d:/file.txt")){ //d드라이브에 파일 생성
String str = "집에 가고 싶어요...";
byte[] bytes = str.getBytes();
for(int i = 0; i < bytes.length; i++){
fos.write(bytes[i]);
}
}catch(Exception e){
e.printStackTrace();
}
}
ThrowException 예외 발생시키기
try {
throw new IOException();
} catch (IOException e) {
e.printStackTrace();
} //강제로 예외 발생시키기
// NullPointerException : 변수에 null이 들어있어서 발생된다
// String str = null;
// System.out.println(str.equals(""));
// IndexOutOfBoundsException : 배열의 인덱스를 벗어나서 발생된다.
int[] a = new int[10];
for(int i = 0; i <= a.length; i++){
System.out.println(a[i]);
}
//파일 이름으로 파일 찾기 : Ctrl + Shift + r
}
public class ThrowsException {
//예외 선언 방법!
public static void main(String[] args) {
try {
method();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void method() throws IOException {
//예외선언 : 이 메서드를 호출했을 때 예외가 발생할 가능성이 있다는 걸 알려준다. -> 메서드 뒤에 throws 예외종류 입력
throw new IOException(); //선언된 예외는 처리하지 않아도 된다.(예외처리는 메서드를 호출한 곳에서)
}
}