(1) 에러(Error): 메모리와 같은 하드웨어상에서의 문제, 개발자와 자바 프로그램이 control할 수 없음 -> JVM이 프로그램을 반드시 종료시켜야 함
ex. OutOfMemoryError, StackOverflowError
(2) 예외(Exception): 개발자가 control할 수 있는 문제, 예외는 JVM이 처리해줌(예외 메시지 출력 및 프로그램 종료)
(i) Checked Exception: 반드시 예외 처리를 해야하는 예외로 처리하지 않으면 컴파일 에러 발생
ex. IOExeption
(ii) Runtime Exception: 반드시 예외 처리를 할 필요는 없음
ex. ArithmeticException
Scanner kb = new Scanner(System.in);
try {
System.out.print("a/b... a? ");
int n1 = kb.nextInt();
System.out.print("a/b... b? ");
int n2 = kb.nextInt();
System.out.printf("%d / %d = %d \n", n1, n2, n1 / n2);
} catch (Exception e){
// Exception도 객체임
// 에러가 발생했을 때 처리하는 구문
e.printStackTrace(); // 에러났을 때의 문구를 뿌려줌, 디버깅을 위해서 넣어줌
// JVM이 Exception이라는 객체 생성을 시켜줌 -> 객체의 printStackTrace를 사용할 수 있게 함
System.out.println(e.getMessage());
} finally {
System.out.println("finally 실행");}
public static void main(String[] args) {
try {
md1(); // md1에서 발생한 에러가 넘어옴
} catch(IOException e) {
e.printStackTrace();
}
}
public static void md1() throws IOException {
md2(); // md2에서 말생한 에러가 넘어옴
}
public static void md2() throws IOException {
Path file = Paths.get("C:\\javastudy\\Simple.txt");
BufferedWriter writer = null;
writer = Files.newBufferedWriter(file);
writer.write('A');
writer.write('Z');
if(writer != null){
writer.close();
}
}
cf) throw: exception을 발생시키는 키워드, 예를 들어 parseInt의 경우 정수가 아닌 다른 문자열을 받으면 exception을 발생시켜 프로그램이 중단된다.
int num = Integer.parseInt(numStr);
parseInt의 소스코드의 throw -> 적절하지 않은 인자(string 등)가 전달되었을 때 예외를 출력하도록 함
public static int parseInt(String s, int radix) throws NumberFormatException
{
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
....
}
public class Example1{
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
try {
System.out.print("a/b... a? ");
int n1 = kb.nextInt();
System.out.print("a/b... b? ");
int n2 = kb.nextInt();
System.out.printf("%d / %d = %d \n", n1, n2, n1 / n2); // 이 값은 안 뿌림
} catch (ArithmeticException e){
e.printStackTrace(); // 에러났을 때의 문구를 뿌려줌, 디버깅을 위해서 넣어줌
// JVM이 ArithmeticException이라는 객체 생성을 시켜줌 -> 객체의 printStackTrace를 사용할 수 있게 함
System.out.println(e.getMessage());
} catch (InputMismatchException e){
e.printStackTrace();
System.out.println(e.getMessage());
} catch (Exception e){
// Exception도 객체임
// 에러가 발생했을 때 처리하는 구문
// Exception은 Exception들의 부모 클래스 -> 모든 에러를 처리할 수 있음
// JVM이 위에서 부터 순서대로 확인 Arithmatic -> Input -> 전체 exception
// 제일 마지막으로 배치해야함
e.printStackTrace();
System.out.println(e.getMessage());
} finally {
System.out.println("finally 실행");
// 예외가 없으면 catch 구문을 실행하지 않고 finally를 실행
// 예외가 있어도 catch 구문을 실행한 후 finally 실행
// 에러가 있던 없던 실행해야하는 사항을 finally에 넣어줌
}
// try-catch로 묶어주면 죽지는 않음
System.out.println("try-catch 바깥");
System.out.println("Good bye~~!");
}
}
따라서 제일 처음에 Exception을 이용해서 예외를 처리하면 오류가 발생할 수 있음
try {
System.out.print("a/b... a? ");
int n1 = kb.nextInt();
System.out.print("a/b... b? ");
int n2 = kb.nextInt();
System.out.printf("%d / %d = %d \n", n1, n2, n1 / n2);
} catch (Exception e){
System.out.println(e.getMessage());
} catch (InputMismatchException e){
System.out.println(e.getMessage());
//컴파일 에러 발생
}
RuntimeException에 속하는 exception은 Unchecked Exception이고 그 외는 전부 CheckedException이다.
암기!
(a) RuntimeException: JVM의 정상적인 작동 중에 발생할 수 있는 예외, 코드 실행 중에 인풋 값이 잘못된 경우나 특정 조건에 부합할 때 발생하게 된다.
(b) ArithmeticException: 정수를 0으로 나누었을 경우
(c) ClassCastException: Class 형변환을 적절하지 않게 실행한 경우
(d) ArrayIndexOutOfBoundsException: 배열에 대한(배열을 참조하는) 인덱스가 잘못된 경우