Finally 블록
Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨 — 59개 중 41번째.
finally 블록은 try-catch 블록 이후에 실행되는 코드가 들어 있는 곳으로, 예외가 발생하든 발생하지 않든 항상 실행됩니다. 파일이나 데이터베이스 연결을 닫는 등의 정리 작업에 일반적으로 사용됩니다.
다음은 try-catch-finally 블록의 기본 구조입니다:
try {
// 예외를 발생시킬 수 있는 코드
} catch (ExceptionType e) {
// 예외를 처리하는 코드
} finally {
// 항상 실행되는 코드
}카운터를 사용한 예를 살펴보겠습니다:
int counter = 0;
try {
int result = 10 / 0;
// 이 부분에서 예외가 발생합니다
counter = 1;
} catch (ArithmeticException e) {
counter = 2;
} finally {
counter = 3;
// 이 부분은 항상 실행됩니다
}위의 코드를 실행한 후, counter에는 다음이 포함되어 있습니다:
3
챌린지
쉬움processNumber라는 이름의 메서드를 생성하세요. 이 메서드는 두 개의 인수를 받습니다:
- 정수로 변환할 String (
number) - 예외를 발생시킬지 결정하는 boolean (
shouldThrow)
메서드는 다음을 수행해야 합니다:
- result 변수를 0으로 초기화
- try 블록에서:
- shouldThrow가 true이면 10을 0으로 나누기
- 그렇지 않으면 number 문자열을 정수로 변환하여 result에 저장
- catch 블록에서: result를 -1로 설정
- finally 블록에서: result에 100을 더하기
- result를 문자열로 반환
치트 시트
finally 블록은 try-catch 블록 이후에 실행되며, 예외가 발생하든 발생하지 않든 상관없이 실행됩니다. 정리 작업에 사용됩니다.
기본 구조:
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that always executes
}카운터를 사용한 예제:
int counter = 0;
try {
int result = 10 / 0; // throws exception
counter = 1;
} catch (ArithmeticException e) {
counter = 2;
} finally {
counter = 3; // always executes
}
// counter = 3직접 해보기
import java.util.Scanner;
public class Main {
public static String processNumber(String number, boolean shouldThrow) {
// 여기에 코드를 작성하세요
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String number = scanner.nextLine();
boolean shouldThrow = Boolean.parseBoolean(scanner.nextLine());
System.out.println(processNumber(number, shouldThrow));
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.