logo

Java 사용자 정의 예외

Java에서는 Exception 클래스의 파생 클래스인 자체 예외를 만들 수 있습니다. 자체 예외를 생성하는 것을 사용자 정의 예외 또는 사용자 정의 예외라고 합니다. 기본적으로 Java 사용자 정의 예외는 사용자 필요에 따라 예외를 사용자 정의하는 데 사용됩니다.

InvalidAgeException 클래스가 Exception 클래스를 확장하는 예제 1을 고려해 보세요.

자바 long에서 int로

사용자 정의 예외를 사용하면 고유한 예외와 메시지를 가질 수 있습니다. 여기서는 슈퍼클래스의 생성자, 즉 우리가 생성한 객체에 대해 getMessage() 메소드를 사용하여 얻을 수 있는 예외 클래스의 생성자에 문자열을 전달했습니다.

이 섹션에서는 Java 프로그램에서 사용자 정의 예외가 구현되고 사용되는 방법을 알아봅니다.

사용자 정의 예외를 사용하는 이유는 무엇입니까?

Java 예외는 프로그래밍에서 발생할 수 있는 거의 모든 일반적인 유형의 예외를 다룹니다. 그러나 때로는 사용자 정의 예외를 생성해야 할 때도 있습니다.

다음은 사용자 정의 예외를 사용하는 몇 가지 이유입니다.

bfs를 위한 뭔가
  • 기존 Java 예외의 하위 집합을 포착하고 특정 처리를 제공합니다.
  • 비즈니스 로직 예외: 비즈니스 로직 및 워크플로와 관련된 예외입니다. 애플리케이션 사용자나 개발자가 정확한 문제를 이해하는 데 유용합니다.

사용자 정의 예외를 생성하려면 java.lang 패키지에 속한 Exception 클래스를 확장해야 합니다.

WrongFileNameException이라는 사용자 정의 예외를 생성하는 다음 예를 고려하십시오.

 public class WrongFileNameException extends Exception { public WrongFileNameException(String errorMessage) { super(errorMessage); } } 

참고: 문자열을 오류 메시지로 사용하는 생성자를 작성해야 하며 이를 부모 클래스 생성자라고 합니다.

예시 1:

Java 사용자 정의 예외의 간단한 예를 살펴보겠습니다. 다음 코드에서 InvalidAgeException의 생성자는 문자열을 인수로 사용합니다. 이 문자열은 super() 메서드를 사용하여 상위 클래스 Exception의 생성자에 전달됩니다. 또한 Exception 클래스의 생성자는 매개변수를 사용하지 않고 호출할 수 있으며 super() 메소드 호출은 필수가 아닙니다.

TestCustomException1.java

 // class representing custom exception class InvalidAgeException extends Exception { public InvalidAgeException (String str) { // calling the constructor of parent Exception super(str); } } // class that uses custom exception InvalidAgeException public class TestCustomException1 { // method to check the age static void validate (int age) throws InvalidAgeException{ if(age <18){ throw an object of user defined exception new invalidageexception('age is not valid to vote'); } else { system.out.println('welcome main method public static void main(string args[]) try calling the validate(13); catch (invalidageexception ex) system.out.println('caught exception'); printing message from invalidageexception system.out.println('exception occured: ' + ex); system.out.println('rest code...'); < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/exception-handling/13/java-custom-exception.webp" alt="Java Custom Exception"> <h3>Example 2:</h3> <p> <strong>TestCustomException2.java</strong> </p> <pre> // class representing custom exception class MyCustomException extends Exception { } // class that uses custom exception MyCustomException public class TestCustomException2 { // main method public static void main(String args[]) { try { // throw an object of user defined exception throw new MyCustomException(); } catch (MyCustomException ex) { System.out.println(&apos;Caught the exception&apos;); System.out.println(ex.getMessage()); } System.out.println(&apos;rest of the code...&apos;); } } </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/exception-handling/13/java-custom-exception-2.webp" alt="Java Custom Exception"> <hr></18){>

산출:

Java 사용자 정의 예외