Try-Catch 기본
Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨 — 59개 중 40번째.
Java에서 try-catch blocks는 프로그램 실행 중 발생할 수 있는 exceptions (errors)를 처리하는 데 사용됩니다. 예외를 throw할 수 있는 코드는 try block에 들어가고, 오류 처리 코드는 catch block에 들어갑니다.
다음은 try-catch 블록의 기본 구조입니다:
try {
// 예외를 발생시킬 수 있는 코드
} catch (ExceptionType e) {
// 예외를 처리하는 코드
}Integer.parseInt()로 실제 작동하는 것을 보겠습니다. 이는 String을 정수로 변환합니다:
String text = "abc";
try {
int number = Integer.parseInt(text);
System.out.println(number);
} catch (NumberFormatException e) {
System.out.println("Error: Not a valid number");
}위의 코드를 실행한 후 출력은 다음과 같습니다:
Error: Not a valid number
챌린지
쉬움divideNumbers라는 이름의 메서드를 생성하세요. 이 메서드는 세 개의 인수를 받습니다:
- 첫 번째 숫자를 나타내는 String (
num1) - 두 번째 숫자를 나타내는 String (
num2) - 배열 인덱스를 나타내는 정수 (
index)
메서드는 다음을 수행해야 합니다:
- 크기가 2인 배열을 생성하세요
- num1의 파싱된 정수 값을 num2의 파싱된 정수 값으로 나눈 결과를 주어진 인덱스에 저장하세요
- 주어진 인덱스의 값을 반환하세요
- 모든 가능한 예외를 적절한 오류 메시지로 처리하세요
반환 메시지는 다음과 같아야 합니다:
NumberFormatException의 경우: "Error: Invalid number format"ArithmeticException의 경우: "Error: Division by zero"ArrayIndexOutOfBoundsException의 경우: "Error: Invalid array index"- 성공적인 작업의 경우: 결과를 문자열로 반환하세요
치트 시트
try-catch 블록은 프로그램 실행 중 발생할 수 있는 예외(오류)를 처리합니다. 예외를 발생시킬 수 있는 코드는 try 블록에, 오류 처리 코드는 catch 블록에 들어갑니다.
기본 구조:
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}Integer.parseInt()를 사용한 예제:
String text = "abc";
try {
int number = Integer.parseInt(text);
System.out.println(number);
} catch (NumberFormatException e) {
System.out.println("Error: Not a valid number");
}일반적인 예외 유형:
NumberFormatException- 잘못된 숫자 형식ArithmeticException- 0으로 나누기ArrayIndexOutOfBoundsException- 잘못된 배열 인덱스
직접 해보기
import java.util.Scanner;
public class Main {
public static String divideNumbers(String num1, String num2, int index) {
// 여기에 코드를 작성하세요
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String num1 = scanner.nextLine();
String num2 = scanner.nextLine();
int index = Integer.parseInt(scanner.nextLine());
System.out.println(divideNumbers(num1, num2, index));
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.