Java에서 고유한 예외를 생성할 수 있으며 이를 사용자 정의 예외 또는 사용자 정의 예외라고 합니다.
사용자 정의 예외를 생성하려면 위에서 언급한 클래스 중 하나를 확장하십시오. 메시지를 표시하려면 toString() 재정의 메서드를 호출하거나 문자열 형식의 메시지를 무시하고 슈퍼클래스 매개변수화된 생성자를 호출합니다.
MyException(String msg){
super(msg);
}
Or,
public String toString(){
return " MyException [Message of your exception]";
} 그런 다음 이 예외가 발생해야 하는 다른 클래스의 모든 위치에서 생성된 사용자 정의 예외 클래스의 개체를 만들고 throw 키워드를 사용하여 예외를 throw합니다.
MyException ex = new MyException ();
If(condition……….){
throw ex;
} 사용자 정의 선택 및 사용자 정의 선택 취소
-
모든 예외는 Throwable의 자식이어야 합니다.
-
핸들 또는 선언 규칙에 의해 자동으로 적용되는 확인된 예외를 작성하려면 예외를 확장해야 합니다. 수업.
-
런타임 예외를 작성하려면 RuntimeException을 확장해야 합니다. 수업.
예:맞춤 검사 예외
다음 Java 프로그램은 사용자 지정 검사 예외를 생성하는 방법을 보여줍니다.
import java.util.Scanner;
class NotProperNameException extends Exception {
NotProperNameException(String msg){
super(msg);
}
}
public class CustomCheckedException {
private String name;
private int age;
public static boolean containsAlphabet(String name) {
for (int i = 0; i < name.length(); i++) {
char ch = name.charAt(i);
if (!(ch >= 'a' && ch <= 'z')) {
return false;
}
}
return true;
}
public CustomCheckedException(String name, int age){
if(!containsAlphabet(name)&&name!=null) {
String msg = "Improper name (Should contain only characters between a to z (all small))";
NotProperNameException exName = new NotProperNameException(msg);
throw exName;
}
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("Enter the name of the person: ");
String name = sc.next();
System.out.println("Enter the age of the person: ");
int age = sc.nextInt();
CustomCheckedException obj = new CustomCheckedException(name, age);
obj.display();
}
} 컴파일 타임 예외
컴파일 시 위의 프로그램은 다음과 같은 예외를 생성합니다.
CustomCheckedException.java:24: error: unreported exception NotProperNameException; must be caught or declared to be thrown throw exName; ^ 1 error
예:사용자 지정 unChecked 예외
사용자 정의 예외가 상속하는 클래스를 RuntimeException으로 변경하기만 하면 런타임에 던져질 것입니다.
class NotProperNameException extends RuntimeException {
NotProperNameException(String msg){
super(msg);
}
} 이전 프로그램을 실행하면 NotProperNameException 클래스를 위의 코드로 대체하여 실행하면 다음과 같은 런타임 예외가 발생합니다.
런타임 예외
Enter the name of the person: Krishna1234 Enter the age of the person: 20 Exception in thread "main" july_set3.NotProperNameException: Improper name (Should contain only characters between a to z (all small)) at july_set3.CustomCheckedException.<init>(CustomCheckedException.java:25) at july_set3.CustomCheckedException.main(CustomCheckedException.java:41)