>  기사  >  Java  >  Java의 사용자 정의 예외

Java의 사용자 정의 예외

王林
王林앞으로
2023-08-24 11:41:082012검색

Java의 사용자 정의 예외

Java에서는 사용자 정의 예외 또는 사용자 정의 예외라고 하는 고유한 예외를 만들 수 있습니다.

사용자 정의 예외를 생성하려면 위 클래스 중 하나를 확장하세요. 메시지를 표시하려면 toString() 메서드를 재정의하거나 문자열 형식의 메시지를 우회하여 매개변수화된 슈퍼클래스 생성자를 호출하세요.

MyException(String msg){
   super(msg);
}
Or,
public String toString(){
   return " MyException [Message of your exception]";
}

그런 다음 이 예외를 발생시켜야 하는 다른 클래스에서 생성한 사용자 정의 예외 클래스의 객체를 생성하고 throw 키워드를 사용하여 예외를 발생시킵니다.

MyException ex = new MyException ();
If(condition……….){
   throw ex;
}

사용자 지정 확인 예외 및 사용자 지정 확인되지 않은 예외

  • 모든 예외는 Throwable의 하위 클래스여야 합니다.

  • Handle 또는 Declare 규칙에 의해 자동으로 적용되는 확인된 예외를 작성하려면 Exception 클래스를 확장해야 합니다.

  • 런타임 예외를 작성하려면 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 >= &#39;a&#39; && ch <= &#39;z&#39;)) {
            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

예: 사용자 정의 확인되지 않은 예외

사용자 정의 예외가 상속하는 클래스를 RuntimeException으로 변경하면 런타임에 해당 클래스가 발생합니다

class NotProperNameException extends RuntimeException {
   NotProperNameException(String msg){
      super(msg);
   }
}

If you 위 프로그램을 실행하고 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)

위 내용은 Java의 사용자 정의 예외의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제