예외 처리 ( Exception )
package exception;
import java.util.Scanner;
public class Ex01 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x, y, result = 0;
System.out.print("수 입력 : ");
x = input.nextInt();
System.out.print("수 입력 : ");
y = input.nextInt();
try {
result = x / y ;
// try 코드에서 문제가 발생하면 catch 로 넘어간다
// try 에서 문제가 없다면 catch 를 진행하지 않고 다음 코드로 넘어간다
}catch(ArithmeticException e) {
// 0 으로는 나눌 수 없는 예외를 처리
System.out.println("문제 발생");
System.out.println("0으로 나눌 수 없음");
}
System.out.println("결과 : " + result);
}
}
발생하는 예외와 일치하는 예외로 처리해줘야 한다
( 예외 클래스들의 부모 클래스인 Exception 으로 통합하여 예외처리도 가능하다 )
package exception;
import java.util.Scanner;
public class Ex02 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
while(true) {
System.out.print("수 입력 : ");
num = input.nextInt();
try {
System.out.println("결과 : " + (100/num));
} catch(Exception e) {
// Exception 은 예외들의 부모 클래스
System.out.println(e);
System.err.println("에러 : " + e); // 빨간 글씨로 출력
// java.lang.ArithmeticException: / by zero
// 에러 : java.lang.ArithmeticException: / by zero
}
}
}
}
예외 처리 예시
package exception;
import java.util.ArrayList;
public class Ex03 {
public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<>();
arr.add("111"); // index : 0
arr.add("222"); // index : 1
arr.add("333"); // index : 2
for(int i=0; i<=arr.size(); i++) {
// arr.size 의 크기와 같아지면 index(3) 까지 출력 명령이 들어가는데
// 이때 해당 인덱스에 값이 없기 때문에 오류 출력
// 이때 예외가 발생되는 문장을 콘솔창에서 찾아 try / catch 사용
try {
System.out.println(arr.get(i));
} catch(IndexOutOfBoundsException e) {
System.out.println(e);
// java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
}
}
System.out.println("다음 문장 실행!!!");
}
}
예외 처리 예시
package exception;
import java.util.ArrayList;
public class Ex03 {
public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<>();
arr.add("111"); // index : 0
arr.add("222"); // index : 1
arr.add("333"); // index : 2
for(int i=0; i<=arr.size(); i++) {
// arr.size 의 크기와 같아지면 index(3) 까지 출력 명령이 들어가는데
// 이때 해당 인덱스에 값이 없기 때문에 오류 출력
// 이때 예외가 발생되는 문장을 콘솔창에서 찾아 try / catch 사용
try {
int n1 = 10, n2 = 0;
System.out.println(n1/n2);
System.out.println(arr.get(i));
} catch(IndexOutOfBoundsException e) {
System.out.println(e);
// java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
} catch(ArithmeticException e) {
System.out.println(e);
// java.lang.ArithmeticException: / by zero
}
}
System.out.println("다음 문장 실행!!!");
}
}
예외 처리는 오버라이드 ( override ) 를 사용하여 각자 발생하는 예외를 매개변수로 갖는 메소드로 향하게 설정이 가능하다
package exception;
import java.util.Scanner;
public class Ex05 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x;
System.out.println("수 입력");
x = sc.nextInt();
try {
int result = 10 / x;
System.out.println("결과 : " + result);
return;
}catch (Exception e) {
// 예외가 발생된 내용을 자세하게 출력
e.printStackTrace();
}finally {
// finally 는 try 가 실행되든지 catch 가 실행되든지
// 무조건 실행되는 코드
// return 으로 해당 코드를 종료해도 finally 는 무조건적으로 실행된다
System.out.println("finally 실행");
sc.close();
// finally 를 사용하여 Scanner 스트림을 무조건 종료시키는 코드 실행
}
System.out.println("다음 문장들 실행!!!");
}
}
e.printStackTrace(); - 예외의 자세한 내용을 출력
finally - 예외가 발생되던지 발생되지 않던지 해당 코드는 진행이 된다
( finally 는 try/catch 에만 사용할 수 있는 것이 아니므로 꼭 실행해야 하는 코드가 있다면 finally 처리를 해주면 된다 )
예외 전가
package exception;
public class Ex07 {
public static void main(String[] args) throws InterruptedException {
// 예외 전가를 사용하여 예외 처리
// 예외처리를 해줘야 하는 Thread.sleep(); 메소드
// 예외처리 해주지 않으면 컴파일 오류가 발생한다
Thread.sleep(1000);
}
}
예외 전가
package exception;
class Test06{
public void test1() throws InterruptedException {
System.out.println("1111");
// test2() 메소드에서 예외를 전가당했으므로 예외가 발생 > throws 로 예외 전가
test2();
}
public void test2() throws InterruptedException {
System.out.println("2222");
// 첫 예외 발생 > throws 로 예외 전가
Thread.sleep(1000);
}
}
public class Ex06 {
public static void main(String[] args) throws InterruptedException {
Test06 t = new Test06();
// t.test1() 메소드에서 예외를 전가당했으므로 예외가 발생 > throws 로 예외 전가
t.test1();
// 1111
// 2222
}
}
예외 전가의 문제점
( 메소드를 호출하여 사용할때 해당 메소드에서 예외를 전가했다면 호출한 클래스에서도 예외를 처리해줘야 한다 )
( 만약 최초 예외가 발생된 곳에서 try / catch 로 개별로 예외를 처리해줬다면 해당 메소드를 호출해도 호출한 클래스에서는 예외가 발생하지 않는다 )
강제 예외
package exception;
import java.util.Scanner;
public class Ex08 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age = 0;
System.out.print("나이 입력 : ");
try {
age = sc.nextInt();
if(age < 0) {
throw new Exception("음수는 입력불가!!!");
}
} catch (Exception e) {
// e.printStackTrace();
System.out.println(e.getMessage());
}
System.out.println("당신의 나이는 : " + age);
}
}
수를 음수로 입력받으면 강제로 예외로 던지는 형태
728x90
'국비지원_핀테크' 카테고리의 다른 글
13일차_ [java] 업캐스팅 ( upcasting ), 다운캐스팅 ( downcasting ) (0) | 2024.02.21 |
---|---|
13일차_ [java] 오버라이딩 ( Overriding ), final (1) | 2024.02.21 |
12일차_ [java] 상속 ( Inheritance ) (0) | 2024.02.20 |
11일차_ [java] 미니 실습 ( 사용 시간 계산기, 스탑워치 ) (0) | 2024.02.19 |
11일차_ [java] 미니 실습 (0) | 2024.02.19 |