Programming/Java
[기초] 예외 처리
devpine
2019. 12. 19. 22:30
반응형
예외 처리
- 1) try{ } catch(Exception e){ } finally{ }
- 2) throws Exception
public class Main {
public static void main(String[] args) {
int i =10;
int j =0;
try{
int k = divide(i,j);
System.out.println(k);
}catch(ArithmeticException e){
System.out.println("0으로 나눌 수 없음.");
}finally{
System.out.println("----끝----");
}
}
public static int divide(int i ,int j) throws ArithmeticException{
int k = i/j;
return k;
}
}
예외 발생시키기
- throw new Exception("~");
public class Main {
public static void main(String[] args) {
int i =10;
int j =0;
try{
int k = divide(i,j);
System.out.println(k);
}
catch(IllegalArgumentException e){
System.out.println("0으로 나누면 안 됩니다...");
}
}
public static int divide(int i ,int j) throws IllegalArgumentException{
if(j==0){
throw new IllegalArgumentException("0으로 나눌 수 없습니다!! ");
}
int k = i / j;
return k;
}
}
사용자 정의 Exception
public class BizException extends RuntimeException {
public BizException(String msg){
super(msg);
}
public BizException(Exception e){
super(e);
}
}
public class BizService {
public void bizMethod(int i) throws BizException{
System.out.println("비지니스 메소드 시작");
if(i<0)
throw new BizException("매객변수는 0 이상이어야 합니다.");
System.out.println("비지니스 베소드 종료");
}
}
public class Main {
public static void main(String[] args) {
BizService biz = new BizService();
biz.bizMethod(5);
biz.bizMethod(-3);
}
}
이 글은 아래 강의를 수강하고 개인적으로 정리한 글입니다.
https://programmers.co.kr/learn/courses/5
자바 입문 | 프로그래머스
평가 4.9 33개의 평가 ★★★★★31 ★★★★1 ★★★1 ★★0 ★0 김세윤 2019.12.03 18:36 박성근 2019.11.28 02:41 정일영 2019.11.14 00:02 APEACH 2019.10.28 12:16 최재욱 2019.10.12 20:16 리뷰 더보기
programmers.co.kr
반응형