[Java_Basic]예외처리(윤성우의 열혈 Java 프로그래밍)
예외
예외적인 상황. 문법 오류가 아닌 정상적이지 않은 상황. 일반적인 예외 상황이란 사용자가 만드는 예외상황
예외 처리
예외 상황에 대한 처리를 의미. 자바는 예외처리 메커니즘을 제공한다.
import java.util.Scanner;
class ExceptionCase{
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
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);
System.out.println("Good bye~~!");
}
}


예외 클래스 : 예외 상황을 알리기 위해 만들어진 클래스
java.lang.ArithmeticException
->수학 연산에서의 오류 상황을 의미하는 예외 클래스
java.util.InputMismatchException
->클래스 scanner를 통한 값의 입력에서의 오류 상황을 의미하는 예외 클래스
try ~ catch
예외의 처리를 위한 코드를 별도로 구분하기 위해 디자인 된 예외처리 메커니즘
try{
...관찰 영역...
}
catch(ArithmericException e){
...처리 영역...
}
try 영역에서 발생한 예외 상황을 catch 영역에서 처리한다.
import java.util.Scanner;
class ExceptionCase2{
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){
System.out.println(e.getMessage());
}
System.out.println("Good bye~~!");
}
}

import java.util.Scanner;
import java.util.InputMismatchException;
class ExceptionCase4{
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){
System.out.println(e.getMessage());
}
catch(InputMismatchException e){
System.out.println(e.getMessage());
}
System.out.println("Good bye~~!");
}
}

import java.util.Scanner;
import java.util.InputMismatchException;
class ExceptionCase5{
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 | InputMismatchException e){
System.out.println(e.getMessage());
}
System.out.println("Good bye~~!");
}
}
Throwable 클래스
java.lang.Throwable 클래스 : 모든 예외 클래스의 최상위 클래스
public String getMessage() -> 예외의 원인을 담고 있느 문자열을 반환
public void printStackTrace() -> 예외가 발생한 위치와 호출된 메소드의 정보를 출력
class ExceptionMessage2 {
public static void md1(int n) {
md2(n, 0);
}
public static void md2(int n1, int n2) {
int r = n1 / n2;
}
public static void main(String[] args) {
try {
md1(3);
}
catch(Throwable e) {
e.printStackTrace();
}
System.out.println("Good bye~~!");
}
}

class ArrayIndexOutOfBounds {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
for(int i = 0; i < 4; i++)
System.out.println(arr[i]);
}
}

class Board { }
class PBoard extends Board { }
class ClassCast {
public static void main(String[] args) {
Board pbd1 = new PBoard();
PBoard pbd2 = (PBoard)pbd1; // OK!
System.out.println(".. intermediate location .. ");
Board ebd1 = new Board();
PBoard ebd2 = (PBoard)ebd1; // Exception!
}
}

class NullPointer {
public static void main(String[] args) {
String str = null;
System.out.println(str); // null 출력
int len = str.length(); // Exception!
}
}

예외 클래스의 구분
Error 클래스를 상속하는 예외 클래스
Exception 클래스를 상속하는 예외 클래스
RuntimeException 클래스를 상속하는 예외 클래스
Error 클래스 / 만들어졌을때 코드레벨의 오류가 아님
VirtualMachineError 가상 머신에 심각한 오류
IOError 입출력 관련해서 코드 수준 복구가 불가능한 오류 발생
RuntimeException 클래스 / 에러같지만 예외인 애매한 클래스
ArithmeticException
ClassCastException
IndexOutOfBoundException
Exception 클래스를 상속하는 예외 클래스
IOException
throws IOException 을 통해 해당 구문에서 발생한 오류를 던져버리겠다 나를 부른 아이에게!
직접 정의하는 예외
논리적인 예외일 경우
class ReadAgeException extends Exception{
public ReadAgeException(){
super("유효하지 않은 나이가 입력되었습니다.");
} //Throwable 클래스의 getMessage 메소드가 반환할 문자열 지정
}
import java.util.Scanner;
class ReadAgeException extends Exception {
public ReadAgeException() {
super("유효하지 않은 나이가 입력되었습니다.");
}
}
class MyExceptionClass {
public static void main(String[] args) {
System.out.print("나이 입력: ");
try {
int age = readAge();
System.out.printf("입력된 나이: %d \n", age);
}
catch(ReadAgeException e) {
System.out.println(e.getMessage());
}
}
public static int readAge() throws ReadAgeException {
Scanner kb = new Scanner(System.in);
int age = kb.nextInt();
if(age < 0)
throw new ReadAgeException();
return age;
}
}
if(age < 0)
throw new ReadAgeException();
직접 예외의 상황을 설정함
finally 구문
마지막에 담기 위한 구문
try{...
}
finally{...
}
또는
try{...
}
catch(Exception name){...
}
finally{...
}
try-with-resources
try 구문을 빠져 나갈 때, 다음 문장을 안정적으로 자동 실행
writer.close();