사용자 정의 예외
Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨 — 59개 중 43번째.
Exception 클래스를 확장하여 자신만의 예외 클래스를 만들 수 있습니다. 이는 애플리케이션에서 특정 유형의 오류를 처리해야 할 때 유용합니다.
사용자 정의 예외를 만드는 방법은 다음과 같습니다:
public class AgeException extends Exception {
public AgeException(String message) {
super(message);
}
}그리고 사용 방법은 다음과 같습니다:
if (age < 0) {
throw new AgeException("Invalid age: " + age);
}위의 코드를 age = -5로 실행한 후, 프로그램은 다음을 던집니다:
AgeException: Invalid age: -5
챌린지
쉬움EmailException이라는 이름의 사용자 정의 예외 클래스를 만들고, 하나의 인수를 받는 validateEmail이라는 메서드를 만드세요:
- 검증할 String (
email)
이 메서드는 다음 메시지와 함께 사용자 정의 예외를 발생시켜야 합니다:
- email이 null인 경우: "Email cannot be null"
- email이 비어 있는 경우: "Email cannot be empty"
- email에 @가 포함되지 않은 경우: "Email must contain @"
- email에 @ 앞에 텍스트가 없는 경우: "Email must have a local part"
- 검증이 통과한 경우: "Valid email"을 반환
치트 시트
Exception 클래스를 확장하여 사용자 정의 예외를 생성하세요:
public class AgeException extends Exception {
public AgeException(String message) {
super(message);
}
}throw 키워드를 사용하여 사용자 정의 예외를 던지세요:
if (age < 0) {
throw new AgeException("Invalid age: " + age);
}직접 해보기
import java.util.Scanner;
class EmailException extends Exception {
public EmailException(String message) {
super(message);
}
}
public class Main {
public static String validateEmail(String email) throws EmailException {
// 여기에 코드를 작성하세요
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String email = scanner.nextLine();
if (email.equals("null")) {
email = null;
}
try {
System.out.println(validateEmail(email));
} catch (EmailException e) {
System.out.println(e.getMessage());
}
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.