Java 에는 여러 Exception 들이 있습니다. 입출력에서 발생하는 IOException, 산술 연산중 발생하는 ArithmethicException(ex. 0으로 나누었을 때) 등등..
여러 Exception 중 IOException 과 ArithmethicException, 인위적인 Exception 처리 방법을 알아보겠습니다.
1. IOException
다음 코드에서 BufferedReader 와 System.in.read() 는 IOException 을 발생시키므로 메인메소드 뒤에 throws IOException 을 추가해주면 컴파일이 되고 Exception 처리가 자동으로 됩니다.
import java.io.*; public class Exception { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("이름을 입력해 주세요 : "); String name = in.readLine(); System.out.print("학년을 입력해 주세요 : "); int grade = System.in.read(); } }
2. ArithmethicException
ArithmeticException 은 산술적인 연산을 할 때 발생하는 Exception 으로 가장 대표적인 예는 0으로 나눌때 발생하는 Exception 입니다.
import java.io.*;
public class Exception {
public static void main(String[] args){
int a=3, b=0;
int c = divide(a,b);
System.out.println(c);
}
public static int divide(int a, int b){
return a/b;
}
}
이 코드를 컴파일 하게 되면 java.lang.ArithmeticException 이 발생하게 됩니다.
이 코드는 분모를 0으로 초기화 해서 나누어주었지만 분모 분자를 입력받아 연산하게 되면 분모가 0이 입력이 되면 Exception이 발생하게 되겠죠.
ArithmeticException 을 해결하기 위해서는 try, catch 문을 사용해서 해결합니다.
import java.io.*; public class Exception { public static void main(String[] args){ int a=3, b=0; try{ int c = divide(a,b); System.out.println(c); } catch(java.lang.ArithmeticException e){ System.out.println("분모가 0입니다."); } } public static int divide(int a, int b){ return a/b; } }
이렇게 try catch 문으로 해결해 주시면 됩니다.
3. 인위적인 Exception
컴파일 상에서의 Exception이 아닌 우리가 프로그래밍을 하면서 인위적으로 Exception을 발생시켜야할 경우가 생깁니다. 예를 들면 편의점에서 물건을 사고 체크카드로 결제를 하는데 체크카드에 들어있는 돈이 물건의 가격보다 적게 들어있다면 결제가 되지 않겠죠. 비슷한 예로 현금 인출을 하는데 계좌의 돈이 뽑으려는 돈보다 적으면 인출이 되지 않겠죠. 이럴 때 인위적인 Exception을 발생시켜줘야 합니다.
인위적인 Exception은 클래스 끼리 넘겨주게 되는데 Exception을 넘겨주는 메소드 뒤에 throws Exception 을 적어주고 메소드 내부에 new throw Exception("에러메세지"); 이러한 방법으로 Exception을 넘겨주게 됩니다. Exception을 받는 클래스에서 try catch 문을 통해 에러메세지를 받아서 처리하게 됩니다.
'Com > Java' 카테고리의 다른 글
[Java] 클래스의 정적 필드 / 정적 메소드 / Static Field / Static Method (0) | 2013.08.05 |
---|---|
[Java] Overriding / 오버라이딩 / Overloading / 오버로딩 (0) | 2013.08.05 |
[Java] 연산에서 형변환 / Casting (0) | 2013.08.05 |
[Java] String[]args / String args[] (1) | 2013.08.04 |
[Java] jdk 5.0 이상 버전의 for문 추가기능 (1) | 2013.08.04 |