try ~ catch 문을 사용합니다.try 블록 내에서 예외가 발생할 수 있는 코드를 작성하고, 예외가 발생하면 catch 블록에서 예외 처리를 수행합니다. 예외가 발생하지 않는 경우는 catch 블록을 건너뛰고 프로그램은 정상적으로 실행됩니다.interface ICalculator {
int add(int x, int y);
int sub(int x, int y);
int mul(int x, int y);
int div(int x, int y);
}
public class CalculatorMain {
public static void main(String[] args) {
Calculator cal = new Calculator();
System.out.println(cal.add(6, 5));
System.out.println(cal.sub(6, 5));
System.out.println(cal.mul(6, 5));
System.out.println(cal.div(6, 0));
}
}
interface ICalculator {
int add(int x, int y);
int sub(int x, int y);
int mul(int x, int y);
int div(int x, int y);
}
public class Calculator implements ICalculator {
public int add(int x, int y) {
return x + y;
}
public int sub(int x, int y) {
return x - y;
}
public int mul(int x, int y) {
return x * y;
}
public int div(int x, int y) {
if (y == 0) {
throw new ArithmeticException("/ by zero");
}
return x / y;
}
}
public class CalculatorMain {
public static void main(String[] args) {
Calculator cal = new Calculator();
System.out.println(cal.add(6, 5));
System.out.println(cal.sub(6, 5));
System.out.println(cal.mul(6, 5));
try {
System.out.println(cal.div(6, 0));
} catch (ArithmeticException e) {
System.out.println(e);
}
System.out.println("계산기 종료");
}
}
이 코드는 ICalculator 인터페이스를 구현하는 Calculator 클래스를 정의하고, 이 클래스의 객체 cal을 생성하여 사칙연산을 수행합니다. div 메소드에서 0으로 나누는 경우 ArithmeticException을 발생시키므로, 이를 try-catch 블록으로 처리하여 예외 메시지를 출력합니다.
throws에 대하여 설명하시오.throws는 메소드 시그니처의 일부로, 메소드를 호출하는 클라이언트에게 메소드의 동작 중 어떤 예외가 발생할 수도 있으므로 예외 처리해줘야한다는 것을 알려줍니다. 예를 들어, public void queryDatabase() throws IOException이라는 메소드가 있다면, 이 메소드를 호출하는 코드는 IOException을 처리해야 합니다.
Checked Exception과 Unchecked Exception 설명하시오.Checked Exception: RuntimeException 클래스에 상속하지 않은 것들이고, 예외가 발생할 수 있는 메소드를 사용할 경우 반드시 catch문이나 throw를 정의해서 처리해야 합니다.Unchecked Exception: 프로그램이 실행된 후에 확인할 수 있고, 프로그램의 오류가 있을 때 발생하도록 의도된 것입니다. RuntimeException을 상속받는 Exception 클래스들을 포함합니다¹¹.try {
int num = 6 / 0;
} catch (Exception e) {
e.printStackTrace();
} catch (InputMismatchException e) {
e.printStackTrace();
}
catch 블록의 순서 때문입니다. Exception 클래스는 모든 예외 클래스의 슈퍼클래스이므로, Exception 타입의 catch 블록이 먼저 나오면 그 아래에 있는 catch 블록은 도달할 수 없게 됩니다⁸. 따라서, 더 구체적인 예외 타입의 catch 블록을 먼저 배치하고, 그 다음에 Exception 타입의 catch 블록을 배치해야 합니다.

public static void main(String[] args) {
Path file = Paths.get("C:\\Simple.txt");
BufferedWriter writer= null;
writer = Files.newBufferedWriter(file);
writer.write('A'); // IOException 발생 가능
writer.write('Z'); // IOException 발생 가능
if(writer != null)
writer.close(); // IOException 발생 가능
}
BufferedWriter 객체를 생성하고 사용하는 코드가 try 블록 안에 없습니다. 이로 인해 IOException이 발생하면 프로그램이 비정상적으로 종료됩니다.BufferedWriter 객체를 생성하고 사용하는 코드를 try 블록 안에 넣고, catch 블록에서 IOException을 처리합니다.main 메소드에 throws IOException을 추가하여 예외를 메소드 호출자에게 전달합니다. 이 경우, JVM이 예외를 처리합니다.public static void main(String[] args) {
Path file = Paths.get("C:\\Simple.txt");
BufferedWriter writer = null;
try {
writer = Files.newBufferedWriter(file);
writer.write('A'); // IOException 발생 가능
writer.write('Z'); // IOException 발생 가능
} catch (IOException e) {
e.printStackTrace();
} finally {
if(writer != null) {
try {
writer.close(); // IOException 발생 가능
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
이 코드는 BufferedWriter 객체를 안전하게 사용하고 닫습니다. try 블록에서 IOException이 발생하면 catch 블록에서 이를 처리하고, finally 블록에서 BufferedWriter를 닫습니다. 이렇게 하면 BufferedWriter가 항상 닫히므로 자원 누수를 방지할 수 있습니다.