public class Test022 {
public static void main(String[] args) {
int a = 1;
int b = 0;
System.out.println(a/b);
System.out.println("test");
}
}
다음 코드를 실행했을 때 a/b와 "test"가 출력되지 않는 이유는 JAVA내에서 예외를 발생시켰기 때문이다.
어떤 수도 0으로 나눌 수 없기 때문에 java.lang.ArithmeticException: / by zero 라는 예외를 던졌다.
public class Test022 {
public static void main(String[] args) {
int []arr = {1,2,3,4,5};
for(int i = 0; i < 10; i++) {
System.out.println(arr[i]);
}
}
}
위 코드는 정상적인 코드인가? 그렇지 않다면 어떤 예외를 발생시키는가
배열 arr의 길이는 5이기 때문에 마지막 index는 4다.
그러나 for문을 사용해서 arr의 최대 index를 벗어나는 5를 출력할 수 없기 때문에 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 와 같은 예외가 발생한 것이다.
정리를 하면 JAVA에서 코드를 작성할 때 여러가지 예외가 발생할 수 있으며 별도의 예외처리를 안 한다면 예외를 던지고 프로그램이 강제로 종료가 된다.
그렇다면 어떻게 예외처리를 해야하는가?
try-catch를 사용하면 된다.
try문 안에는 예외가 발생될 수 있는 코드를 작성하고 catch문 안에는 예외가 발생되면 처리해야될 코드를 작성한다.
1. 예외 잡기
public class Test022 {
public static void main(String[] args) {
int []arr = {1,2,3,4,5};
try {
for(int i = 0; i < 10; i++) {
System.out.println(arr[i]);
}
} catch(Exception e) {
System.out.println("예외입니다.");
}
System.out.println("test입니다.");
}
}
try문 안에서 예외가 발생했기 때문에 catch문이 실행됐다.
그렇기 때문에 프로그램이 강제료 동료되지 않고 정상종료 됐다.
하지만 위와 같이 코드를 작성한다면 개발자가 어떤 예외가 발생됐는지 알 수 없기 때문에 안전한코드가 아니다.
2. 예외던지기
public class Test022 {
public static void main(String[] args) {
int []arr = {1,2,3,4,5};
try {
for(int i = 0; i < 10; i++) {
System.out.println(arr[i]);
}
} catch(Exception e) {
throw e;
}
System.out.println("test입니다.");
}
}
catch문 안에 throw e를 작성하면 잡힌 코드가 던져지면서 강제 종료된다. 그러나 강제종료됐기 때문에 다음 코드를 실행하지 않는다.
예외를 던지더라도 반드시 실행시키고 싶은 코드가 있다면 어떻게 작성해야 하는가?
3. finally 사용하기
public class Test022 {
public static void main(String[] args) {
int []arr = {1,2,3,4,5};
try {
for(int i = 0; i < 10; i++) {
System.out.println(arr[i]);
}
System.out.println("try입니다.");
} catch(Exception e) {
throw e;
} finally {
System.out.println("finally입니다.");
}
}
}
finally 안에있는 코드는 예외발생유무와 관계없이 무조건 실행되는 코드다.
따라서 try문에서 예외가 발생함과 동시에 catch가 잡아내기 때문에 "try입니다."는 출력되지 않고 finally문의 "finally입니다."는 출력된다.
4. 예외만들기
그렇다면 JAVA내에 있는 예외 이외에 임의로 예외를 만들어서 발생시킬 수 있을까?
class BalanceException extends Exception{
public void notice() {
System.out.println("잔액이 부족합니다.");
}
}
class Account{
private int balance = 0;
void withdraw(int coin) throws BalanceException{
if(balance-coin<0) throw new BalanceException();
balance = balance - coin;
}
void deposit(int coin) {
balance = balance + coin;
}
void getBalance() {
System.out.println("잔액: "+balance);
}
}
public class Test022 {
public static void main(String[] args) {
Account myAccount = new Account();
try {
myAccount.deposit(500);
myAccount.getBalance();
myAccount.withdraw(700);
myAccount.getBalance();
}
catch(BalanceException e ){
e.notice();
}
}
}
계좌 입출금을 실행하는 코드를 작성했다.
Account클래스는 계좌이며 balance는 잔액이다. Account클래스에는 출금의 withdraw메소드와 입금의 deposit메소드가 있다.
여기서 구현한 예외는 잔액이 부족할 시에 출금을 못하도록 발생되는 것이다.
class BalanceException extends Exception{
public void notice() {
System.out.println("잔액이 부족합니다.");
}
}
우선적으로 예외를 만들었다. 자바의 모든 예외는 Exception클래스로 부터 상속 받았기 때문에 예외를 만든다면 반드시 Exception클래스를 상속받아야 한다.
class Account{
private int balance = 0;
void withdraw(int coin) throws BalanceException{
if(balance-coin<0) throw new BalanceException();
balance = balance - coin;
}
void deposit(int coin) {
balance = balance + coin;
}
void getBalance() {
System.out.println("잔액: "+balance);
}
}
withraw 메소드에서 출금하려고 하는 금액이 잔액보다 많다면 예외가 발생되야 하기 때문에 throw new BalanceException();를 작성함으로써 예외를 던져준다.
try {
myAccount.deposit(500);
myAccount.getBalance();
myAccount.withdraw(700);
myAccount.getBalance();
}
catch(BalanceException e ){
e.notice();
}
예외가 발생할 때 잡아줘야 하기 때문에 코드를 try-catch문으로 작성한다.
잔액이 500이지만 700을 출금하려 하면 예외가 발생한다. catch가 예외를 잡고 BalanceException클래스에 잔액이 부족함을 통지하는 notice메소드를 호출한다.
결과적으로 다음과 같이 출력된다.
'JAVA 기초 정리' 카테고리의 다른 글
JAVA 선택정렬(Selection Sort)와 삽입정렬(Insertion Sort) (0) | 2020.03.19 |
---|---|
JAVA Call by value와 Call by reference (0) | 2020.03.14 |
JAVA Stack과 Queue구현하기 (0) | 2020.03.08 |
JAVA Node로 Doubly Linked List 구현하기 (0) | 2020.03.08 |
JAVA 와일드카드 제네릭(Generic)과 Object 클래스 (0) | 2020.03.07 |
댓글