기존(310)/🏀JavaExcption

java.lang.ArithmeticException: / by zero 에러 해결 방법

조각남자 2022. 8. 30. 09:40

 

 

 

 

java.lang.ArithmeticException: / by zero 에러 나는 원인\

(변경전)

 

정수를 0으로 나누면 예외처리 발생

예를 들어 밑에서

 

su = 0 ; 인데

180/0 = 0 ; 의 값이 나오니 

이런표시가 뜬다..

 

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class asdadasd {
 
    public static void main(String[] args) {
 
        
        Integer math = 100;
        Integer la = 80;
        Integer av = 0;
        Integer su = 0;
        
        
        try {
            
            av = (math+la)/su;
            System.out.println("av =" +av);
        } catch (Exception e) {
               e.printStackTrace();
        }
    
        
        
        
    }
 
}
cs

 

 

java.lang.ArithmeticException: / by zero 에러 나는 원인\

(변경후)

아래에서 2가지만 바꿔주게 된다면 에러처리는 안나게된다.

0의 값이 반환이 안되도록 만들려고

if조건식을 사용함

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class asdadasd {
 
    public static void main(String[] args) {
 
        
        Integer math = 100;
        Integer la = 80;
        Integer av = 0;
        int su = 10// 바뀐곳 0 --> 10 으로
        
        
        try {
            
            if(su!=0) { // if 조건문 추가
                av = (math+la)/su;
                System.out.println("av =" +av);
            } 
            
        } catch (Exception e) {
               e.printStackTrace();
        }
    
        
        
        
    }
 
}
 
cs