> Java > java지도 시간 > 본문

Java 산술 예외

WBOY
풀어 주다: 2024-08-30 16:13:38
원래의
759명이 탐색했습니다.

Java 산술 예외는 런타임 시 코드에서 잘못된 산술 또는 수학적 연산이 발생할 때 발생하는 일종의 확인되지 않은 오류 또는 코드의 비정상적인 결과입니다. 예외라고도 알려진 런타임 문제는 분모가 정수 0이고 JVM이 결과를 평가할 수 없어 프로그램 실행이 종료되고 예외가 발생하는 경우 발생합니다. 예외가 발생한 시점에서 프로그램이 종료되지만 그 이전의 코드가 실행되어 결과가 표시됩니다.

Java 산술 예외의 기본 클래스는 java.lang.RuntimeException 아래에 있는 lang.ArithmeticException입니다.

광고 이 카테고리에서 인기 있는 강좌 JAVA MASTERY - 전문 분야 | 78 코스 시리즈 | 15가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

Java의 ArithmeticException 구조

기본 클래스 ArithmeticException의 구조:

Java 산술 예외

ArithmeticException 생성자

1. ArithmeticException(): 매개변수가 전달되지 않거나 자세한 메시지가 없는 산술 예외를 정의합니다.

2. ArithmeticException(String s): 하나의 매개변수가 전달된 ArithmeticException을 정의합니다.

s:s는 자세한 메시지입니다 

Java에서 ArithmeticException이 어떻게 작동하나요?

다음은 Java ArithmeticException이 발생할 수 있는 두 가지 상황입니다.

  • 정의되지 않은 0과 정수로 나눈 숫자
  • Big Decimal로 끝나지 않는 긴 십진수

1. 정수 0으로 숫자 나누기

숫자를 0으로 나누려고 하면 Java에서 산술 예외가 발생합니다. 다음은 작업을 설명하는 Java 코드입니다.

예시 #1

코드:

package com.java.exception;
public class ArithmeticException
{
void division(int a,int b)
{
int c=a/b;
System.out.println("Division has been successfully done");
System.out.println("Value after division: "+c);
}
public static void main(String[] args)
{
ArithmeticException ex=new ArithmeticException();
ex.division(10,0);
}
}
로그인 후 복사

출력:

Java 산술 예외

  • lang.ArithmeticException: 나누는 동안 Java 언어에서 예외가 발생했습니다.
  • / by zero: ArithmeticException 인스턴스 생성 시 ArithmeticException 클래스에 전달되는 자세한 메시지입니다.

10을 0으로 나누었기 때문에 0은 정수이고 정의되지 않았으므로 위의 산술 예외가 발생합니다.

예시 #2

코드:

//package com.java.exception;
public class ArithmeticException
{
void division(int a,int b)
{
int c=a/b;
System.out.println("Division of a number is successful");
System.out.println("Output of division: "+c);
}
public static void main(String[] args)
{
ArithmeticException ex=new ArithmeticException();
ex.division(10,5);
}
}
로그인 후 복사

출력:

Java 산술 예외

2. 큰 십진수로 끝나지 않는 긴 십진수

Java에는 최대 소수점 이하의 정밀도 자릿수를 나타내는 BigDecimal 클래스가 있습니다. 이 Java 클래스에는 정수, double 및 float와 같은 기본 데이터 유형에서 사용할 수 없는 일부 기능 세트도 있습니다. 이러한 기능은 소수점 이하 자릿수를 제공합니다

아래는 예시용 코드입니다.

예시 #1

코드:

//package com.java.exception;
import java.math.BigDecimal;
public class ArithmeticException
{
public static void main(String[] args)
{
BigDecimal a=new BigDecimal(1);
BigDecimal b=new BigDecimal(6);
a=a.divide(b);
System.out.println(a.toString());
}
}
로그인 후 복사

출력:

Java 산술 예외

위에 작성된 Java 코드에서 큰 소수 클래스는 나눗셈 출력으로 무엇을 해야 할지 모르기 때문에 출력 콘솔에 산술 예외를 던지거나 표시합니다.

"비종료 소수점 확장, 정확한 표현 없음"이라는 자세한 메시지와 함께 예외가 발생합니다.

위의 큰 소수 클래스에 대한 한 가지 가능한 방법은 큰 소수에서 필요한 소수 자릿수를 명시한 다음 값을 명확한 소수 자릿수로 제한하는 것입니다. 예를 들어, c는 숫자를 7번째 소수 정밀도 값

까지 반올림하여 소수점 이하 7자리로 제한해야 합니다.
예시 #2

코드:

//package co.java.exception;
import java.math.BigDecimal;
public class ArithmeticException
{
public static void main(String[] args)
{
BigDecimal a=new BigDecimal(1);
BigDecimal b=new BigDecimal(6);
a=a.divide(b,7,BigDecimal.ROUND_DOWN);// limit of decimal place
System.out.println(a.toString());
}
}
로그인 후 복사

출력:

Java 산술 예외

출력 콘솔에는 결과가 7번째 소수점 값이 있는 숫자로 표시됩니다. 이는 반올림이 제대로 작동함을 의미합니다.

Java ArithmeticException을 피하거나 처리하는 방법은 무엇입니까?

Java Virtual Machine에서 발생한 예외를 처리하는 것을 예외 처리라고 합니다. 예외 처리의 장점은 코드 실행이 중단되지 않는다는 것입니다.

try와 catch의 조합을 사용하여 예외를 처리합니다. 예외를 생성할 수 있는 코드에는 try/catch 블록이 배치됩니다. try/catch 블록 안에 작성된 코드를 보호된 코드라고 합니다.

구문:

try
{
set of statements//protected code
}
catch (exceptionname except)
{
// Catch set of statements---can contain single catch or multiple.
}
로그인 후 복사

ArithmeticException Handling using try & Catch Blocks

  • Write the statements that can throw ArithmeticException with try and catch blocks.
  • When an exception occurs, the execution falls to the catch block from an exception’s point of occurrence. It executes the catch block statement and continues with the statement present after the try and catch blocks. Below is the example:

Code:

public class ExceptionHandled
{
public static void main(String args[])
{
int x =100, y = 0;
int z;
System.out.println("Hello world");
try
{
z = x/y;
System.out.println(z);
}
catch(ArithmeticException except)
{
System.out.println("Avoid dividing by integer 0" + except );
}
System.out.println("Hello class");
System.out.println("Hello there");
}
}
로그인 후 복사

Output:

Java 산술 예외

Hello class and Hello, there are also printed on the output console apart from Hello world. This is the outcome of the exception handling mechanism.

Explanation:

  1. Try, and catchblocks are exception handling keywords in Java used completely used to handle the exception or unchecked error raised in the code without halting the execution of the code.
  2. Detect the trouble creating statements and place them in the try block. When the try block throws the exception, the catch block handles that exception, and the execution of the program goes further to the last statement.
  3. If the try block does not throw the exception, the catch block is simply overlooked.
  4. Run a suitable exception handler or statements in the catch block to handle or detect the exception thrown by the try block successfully.

Conclusion

This article has learned about java arithmetic exception and how to handle the exception under try and catch block. An arithmetic exception occurs most of the time because of the division of a number by integer 0. In this article, I have used a single catch for a single try, but we can also use multiple catch for a single try.

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

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!