예외란 프로그램 실행 중에 예기치 못한 상황에서 발생하는 비정상적인 상황을 가리킵니다.
예외처리란 예외 발생 시 프로그램의 비정상적인 종료대신 계속해서 정상적인 수행을 할 수 있도록 처리하는 것입니다.
프로그램에서 예외도 하나의 객체로 표현되어 일반 객체처럼 클래스를 이용하여 정의되어 사용 가능합니다.
java.lang.Throwable로부터 파생된 클래스로 throws할 수 있습니다.
RuntimeException 클래스의 sub class
- ArithmeticException : 0으로 나누는 경우에 발생
- java.io.IOException : 입출력 동작의 실패
Throwable 클래스의 멤버 메서드를 사용합니다.
public class e1 {
public static void main(String[] args) {
int num1=3, num2=0;
try { //정수를 0으로 나누니 예외 발생 가능성 있음
int result=num1/num2; //exception
System.out.println(result);
}
catch(ArithmeticException ae) { //함수 매개변수 ae
String str=ae.getMessage();
System.err.println(str);
}
}
}
메서드 구현부에 기술하며 예외발생시 예외 처리를 현재 메서드를 호출한 곳으로 양도합니다. 즉, 언젠가는 try~catch문으로 처리해주어야 합니다.
public class e3 {
static int divide(int a, int b) throws ArithmeticException{
int result=a/b;
return result;
//예외 발생시 쓸데없는 값을 반환하는 것이 아닌 오류를 던짐
}
public static void main(String[] args) {
int num1=3, num2=0;
try { //함수로부터 던져진 오류를 main에서 처리함
int result=divide(num1,num2);
System.out.println(result);
}
catch(ArithmeticException ae) {
String str=ae.getMessage();
System.err.println(str);
}
System.out.println("끝");
}
}
프로그래머가 직접 필요한 예외 클래스를 만들어 사용합니다.
//Account.java
public class Account {
protected String accountNo;
protected String name;
protected int balance;
public Account(String accountNo, String name, int balance) {
this.accountNo=accountNo;
this.name=name;
this.balance=balance;
}
public int deposit(int amount) throws MalformedData{
if(amount<0)
throw new MalformedData();
balance+=amount;
return balance;
}
public int withdraw(int amount) throws MalformedData, OBException {
if(amount<0)
throw new MalformedData();
if(balance<amount) {
throw new OBException();
}
balance-=amount;
return amount;
}
public void check() {
System.out.println("잔액 조회 :"+balance);
}
}
//Bank.java
public class Bank {
public static void main(String[] args) {
Account [] banks=new Account[2];
banks[0]=new Account("11","aa",100);
banks[1]=new Account("22","bb",200);
try {
int n=banks[0].deposit(-1000);
}
catch(MalformedData e) {
String str=e.getMessage();
System.err.println(str);
}
try {
int n=banks[1].withdraw(3000);
}
catch(MalformedData e) {
String str=e.getMessage();
System.err.println(str);
}
catch(OBException e) {
String str=e.getMessage();
System.err.println(str);
}
}