본문 바로가기
Java

Try-catch 예외처리

by Ms.Pudding 2022. 1. 7.

Error와 Exception의 차이

 

error는 error가 발생하면 프로그램이 종료되지만,

excpetion은 error가 발생하여도 , excpetion handling(예외처리)을 통해 프로그램이 계속 작동할 수 있게 해준다.

 

자바에서 예외처리는 try-exception을 통해 해준다.

exception에서 printStackTrace() 메소드를 쓰면 어디서 에러가 발생했는지 알려준다.

 

public class TryCatch{
	public static void main(String[] args){
		int num1,num2
	
try{
	num1=0;
	num2=62/num1;
	System.out.println(num2); // 0으로 나누어져서 에러발생
	System.out.println("숫자는 0으로 나눌 수 없다, 에러발생")
}catch(ArithmeticException e){
		//arithmeticException은 수학적으로 성립안되는 에러
		System.out.println("you should not divide number by zero");
}catch(Exception e){
		System.out.println("handles all the generic error exceptions");
		System.out.println("this occurs if the previous error excpeiton not executed");
}


	}
}

 

0으로 나눌 수 없는 수학적 에러가 발생하였으니, 두번째 캐치문이 출력된다. you should not divide number by zero

try문에 있는건 출력안함 

'Java' 카테고리의 다른 글

Arrays.asList()란  (0) 2022.01.07
두 변수의 값 바꾸기 (swap)  (0) 2022.01.07
Super() 메소드  (0) 2022.01.07
super 키워드  (0) 2022.01.07
this참조 변수와 this()메소드  (0) 2022.01.07

댓글