English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
예외는 프로그램 실행 중 발생하는 문제(실행 시간 오류)입니다. 예외가 발생하면 프로그램이 갑자기 중지되고, 예외가 발생한 줄 이후의 코드는 결코 실행되지 않습니다.
Java를 사용하여 자신의 예외를 생성할 수 있으며, 이 예외는 사용자 정의 예외 또는 사용자 정의 예외로 알려집니다.
모든 예외는 Throwable의 서브 클래스여야 합니다.
Handle 또는 Delare Rule이 자동으로 실행하는 검사된 예외를 작성하려면, 확장해야 합니다.Exception클래스.
루틴 시간 예외를 작성하려면, 확장해야 합니다.RuntimeException클래스.
예외 클래스를 확장하여 사용자 정의 예외를 생성하는 것은 필수적이지 않습니다. 대신 Throwable 클래스(모든 예외의 상위 클래스)를 확장하여 예외를 생성할 수 있습니다.
아래의 Java 예제는 AgeDoesnotMatchException이라는 이름의 사용자 정의 예외를 생성하며, 이 예외는 사용자의 나이를 제한합니다.17세대로24세대 사이에서, 예외 클래스를 확장하지 않고 그것을 생성합니다.
import java.util.Scanner; class AgeDoesnotMatchException extends Throwable{ AgeDoesnotMatchException(String msg){ super(msg); } } public class CustomException{ private String name; private int age; public CustomException(String name, int age){ try { if (age<17||age>24) { String msg = "Age is not between 17 및 24"; AgeDoesnotMatchException ex = new AgeDoesnotMatchException(msg); throw ex; } }catch(AgeDoesnotMatchException e) { e.printStackTrace(); } this.name = name; this.age = age; } public void display(){ System.out.println("Name of the Student: ");+this.name ); System.out.println("Age of the Student: ");+this.age ); } public static void main(String args[]) { Scanner sc= new Scanner(System.in); System.out.println("학생의 이름을 입력하세요: "); String name = sc.next(); System.out.println("학생의 연령을 입력하세요, 입력해야 할 값은 17 부터 24 (포함하여 17 및 24): "); int age = sc.nextInt(); CustomException obj = new CustomException(name, age); obj.display(); } }
출력 결과
학생의 이름을 입력하세요: Krishna 학생의 연령을 입력하세요, 입력해야 할 값은 17 부터 24 (포함하여 17 및 24): 30 july_set3.AgeDoesnotMatchException: 연령대는 17 및 24 학생의 이름: Krishna 학생의 연령대: 30 at july_set3.CustomException.<init>(CustomException.java:)17) at july_set3.CustomException.main(CustomException.java:)36)