Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 Throwable 클래스와 해당 메소드의 중요성은 무엇입니까?

<시간/>

던질 수 있음 class는 Java의 모든 오류 및 예외의 상위 클래스입니다. 이 클래스의 인스턴스인 개체는 Java Virtual Machine에 의해 throw됩니다. 또는 던지기 로 던질 수 있습니다. 성명. 마찬가지로 이 클래스나 그 하위 클래스 중 하나는 catch 절의 인수 유형이 될 수 있습니다.

두 하위 클래스의 인스턴스 오류 예외 예외적 상황이 발생했음을 나타내는 데 사용되며, 이러한 인스턴스는 관련 정보를 포함하기 위해 예외적 상황의 맥락에서 생성됩니다.

Throwable 클래스의 일반적으로 사용되는 예외 메소드

  • 공개 문자열 getMessage(): 예외에 대한 메시지 문자열을 반환합니다.
  • 공개 throwable getCause(): 예외의 원인을 반환합니다. 원인을 알 수 없거나 존재하지 않는 경우 null을 반환합니다.
  • 공개 문자열 toString(): 예외에 대한 간단한 설명을 반환합니다.
  • 공용 무효 printStackTrace(PrintStream s): 예외에 대한 간단한 설명(toString() 사용) + 이 예외에 대한 스택 추적을 오류 출력 스트림(System.err)에 인쇄합니다.

class ArithmaticTest {
   public void division(int num1, int num2) {
      try {
         //java.lang.ArithmeticException here.
         System.out.println(num1/num2);
         //catch ArithmeticException here.
      } catch(ArithmeticException e) {
         //print the message string about the exception.
         System.out.println("getMessage(): " + e.getMessage());
         //print the cause of the exception.
         System.out.println("getCause(): " + e.getCause());
         //print class name + “: “ + message.
         System.out.println("toString(): " + e.toString());
         System.out.println("printStackTrace(): ");
         //prints the short description of the exception + a stack trace for this exception.
         e.printStackTrace();
      }
   }
}
public class Test {
   public static void main(String args[]) {
      //creating ArithmaticTest object
      ArithmaticTest test = new ArithmaticTest();
      //method call
      test.division(20, 0);
   }
}

출력

getMessage(): / by zero
getCause(): null
toString(): java.lang.ArithmeticException: / by zero
printStackTrace():
java.lang.ArithmeticException: / by zero
at ArithmaticTest.division(Test.java:5)
at Test.main(Test.java:27)