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

Java에서 ArithmeticException(선택되지 않음)을 처리하는 방법은 무엇입니까?

<시간/>

java.lang.ArithmeticException 확인되지 않은 예외입니다. 자바에서. 일반적으로 java.lang.ArithmeticException:/ by zero가 발생합니다. 두 숫자를 나누려고 시도할 때 발생 분모의 숫자는 0입니다. . 산술 예외 객체는 JVM에 의해 구성될 수 있습니다. .

예시 1

public class ArithmeticExceptionTest {
   public static void main(String[] args) {
      int a = 0, b = 10;
      int c = b/a;
      System.out.println("Value of c is : "+ c);
   }
}

위의 예에서 ArithmeticExeption 분모 값이 0이기 때문에 발생합니다.

  • java.lang.ArithmeticException :분할 중 Java에서 예외가 발생했습니다.
  • / 0으로 :ArithmeticException 에 제공된 세부 메시지입니다. ArithmeticException 생성 중 클래스 개체 .

출력

Exception in thread "main" java.lang.ArithmeticException: / by zero
      at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:5)


ArithmeticException 처리 방법

ArithmeticException 을 처리합시다. 시도하고 잡기 사용 블록.

  • ArithmeticException 을 발생시킬 수 있는 명령문을 둘러싸십시오. 시도하고 잡기 블록.
  • 우리는 잡을 수 있습니다 산술 예외
  • 실행되지 않으므로 프로그램에 필요한 조치를 취합니다. 중단 .

예시 2

public class ArithmeticExceptionTest {
   public static void main(String[] args) {
      int a = 0, b = 10 ;
      int c = 0;
      try {
         c = b/a;
      } catch (ArithmeticException e) {
         e.printStackTrace();
         System.out.println("We are just printing the stack trace.\n"+ "ArithmeticException is handled. But take care of the variable \"c\"");
      }
      System.out.println("Value of c :"+ c);
   }
}

예외 발생하면 실행은 catch로 떨어집니다. 차단 예외가 발생한 시점부터. catch 블록의 명령문을 실행합니다. try and catch 뒤에 있는 문장으로 계속됩니다. 블록.

출력

We are just printing the stack trace.
ArithmeticException is handled. But take care of the variable "c"
Value of c is : 0
java.lang.ArithmeticException: / by zero
        at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:6)
에서 0으로