● 예외 처리(Exception Handling)
- 예외가 발생하면 프로그램이 강제적으로 종료되고, 그 과정에서 사용자 경험이 나빠지거나 데이터 손실이 발생할 수 있다.
- 예외가 발생하더라도 정상적으로 종료되도록 다루는 것
● throw
- 예외를 발생시키는 키워드
● Object 클래스에 존재하는 toString()
- 해당 메소드를 재정의하면, 출력될 때 모습을 정할 수 있다.
실습(throw(1))
1. RuntimeException 클래스를 상속받는 클래스 생성
// 컴파일 오류 : Exception
public class BadWordException extends RuntimeException /*Exception */{
public BadWordException() {}
public BadWordException(String s) {
super(s);
}
}
2. Main.java에서 throw 사용
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("설정할 닉네임을 쓰시오 >> ");
String nick = sc.nextLine();
if(nick.equals("1번")) {
throw new BadWordException("오류 발생 - 1번 오류");
} else if(nick.equals("2번")) {
throw new BadWordException("오류 발생 - 2번 오류");
}
}
}


실습(throw(2))
public class Main2 {
public static void main(String[] args) {
int num = 1;
if(num == 1) {
try {
throw new ArithmeticException("세부 설명");
} catch(ArithmeticException e) {
e.printStackTrace();
System.out.println("예외 발생");
}
}
System.out.println("프로그램 종료");
}
}

실습(toString())
1. toString()을 재정의하여 프로그램 실행하기
(1) Car.java에서 toString()을 Override하기
public class Car {
String name;
@Override
public String toString() {
return name + "의 차";
}
}
(2) Main.java에서 실행
public class Main {
public static void main(String[] args) {
Car c1 = new Car();
c1.name = "김철수";
Car c2 = new Car();
c2.name = "홍길동";
System.out.println(c1);
System.out.println(c2.toString());
}
}

2. toString()을 재정의한 후 요소를 추가하는 메소드를 생성하여 프로그램 실행하기
(1) MyIntArray.java에서 toString()을 Override한 후 요소 추가 메소드 생성하기
public class MyIntArray {
int[] ar = new int[100];
int length = 0; // 실질적 길이
// 요소 추가 메소드
public void add(int idx, int num) {
if(idx < 0 || length <idx) {
throw new ArrayIndexOutOfBoundsException();
}
ar[idx] = num;
length++;
}
@Override
public String toString() {
String res = "{";
for(int i = 0; i < this.length; i++) {
res += ar[i] + ", ";
}
res += "}";
return res;
}
}
(2) Main.java에서 실행
public class Main {
public static void main(String[] args) {
MyIntArray ar = new MyIntArray();
System.out.println(ar);
ar.add(0, 100);
System.out.println(ar);
ar.add(1, 10);
System.out.println(ar);
// ar.add(5, 110); // ArrayIndexOutOfBoundsException 오류 발생
}
}
