[자바 (JAVA)] 48. 예외 처리

귤's avatar
Feb 18, 2025
[자바 (JAVA)] 48. 예외 처리
notion image
notion image
notion image

1. 예외 처리

💡
Exception Handling
  • 코드 작성자가 예기치 않게 발생하는 에러들에 대응할 수 있도록 사전에 방지하는 것이다.
  • 예외 처리를 하면 프로그램의 비정상적인 종료를 방지하여 정상적인 실행 상태를 유지할 수 있다.

Runtime Exception vs Checked Exception

1) Runtime Exception

💡
컴파일 과정에서는 문제를 발견하지 못하고 정상적으로 컴파일이 진행되었으나, 프로그램을 실행 중에 발생하는 오류 사항들을 대체로 예외라고 정의한다.

2) Checked Exception

💡
예외를 잡아서 처리하거나 (try ~ catch), 이게 안되면 예외를 밖으로 던지는 throw 를 필수로 선언해야 한다.

Try - Catch 구조

try { // 예외가 발생할 수 있는 코드 } catch (예외클래스 변수) { // 예외를 처리하는 코드 }
package ex15; public class DivideByZeroOK { public static void main(String[] args) { try { int result = 10 / 0; } catch (Exception e) { System.out.println("괜찮아 : " + e.getMessage()); } } }
package ex15; public class DivideByZeroOK02 { public static void main(String[] args) { try { int result = 10 / 0; System.out.println(result); } catch (ArithmeticException e) { System.out.println("괜찮아 : " + e.getMessage()); } } }
package ex15; public class Run01 { public static int gcd(int a, int b) { //if (b == 0) return a; try { return gcd(b, a % b); } catch (ArithmeticException e) { return a; } } public static void main(String[] args) { int r = gcd(10, 20); // [1,2,5,10], [1,2,4,5,10,20] System.out.println(r); } }

CheckedException 예제

package ex15; public class Check01 { public static void main(String[] args) { System.out.println("시작"); try { Thread.sleep(5000); } catch (InterruptedException e) { // Exception으로 해도 돌아간다. System.out.println("도중에 꺼졌는데 괜찮아"); } System.out.println("끝"); } }
package ex15; import java.io.FileNotFoundException; import java.io.FileReader; public class Check02 { public static void main(String[] args) { try { FileReader file = new FileReader("C:/hello/good.txt"); } catch (FileNotFoundException e) { System.out.println("파일을 내가 직접 C:/hello/good.txt 생성"); } } }

Throw new

package ex15; public class Try01 { public static void main(String[] args) { throw new ArithmeticException("강제로 만든 익셉션"); } // throw new ~ 하면 강제로 터뜨릴 수 있다 }
package ex15; class A { static int start(boolean check) { int r = B.m1(check); return r; } } class B { static int m1(boolean check) { if (check) { return 1; } else { throw new RuntimeException("false 오류남"); } } } public class Try02 { public static void main(String[] args) { try { int r = A.start(false); System.out.println("정상 : " + r); } catch (Exception e) { System.out.println("오류 처리 방법 : " + e.getMessage()); } } }
 
 
Share article

gyul