public class Main {
public static void main(String[] args) {
int arr = new int[10];
try {
// 오류 가능성이 있는 코드
int k = 10/0;
} catch (ArithmeticException e) {
// 오류가 발생할 시 실행되는 코드
System.out.println("0으로 나누면 안됩니다.");
} catch (ArrayIndexOutOfBoundsException e) {
// 상황에 따라 오류의 종류가 다르다.
// catch는 다중 작성이 가능하다.
} finally {
// 오류가 나든 말든 무조건 실행되는 코드
// final은 생략 가능
}
}
}
~~
} catch (Exception e) {
// 오류의 종류에 상관없이 모든 오류를 처리
}

throws ArithmeticExceptionthrow new ArithmeticException("메세지");
public class ExceptionExam2 {
//메소드 호출
public static void main(String[] args) {
int i = 10;
int j = 0;
try{
int k = divide(i, j);
System.out.println(k);
} catch(ArithmeticException e){
System.out.println("0으로 나눌수 없습니다.");
}
}
//메소드 case1
public static int divide(int i, int j) throws ArithmeticException{
int j = 0;
int k = 10 / j;
return k;
}
//메소드 case2
public static int divide(int i, int j) {
int j = 0;
int k = 10 / j;
throw new ArithmeticException("메세지");
}
}
import java.util.Scanner; ※ 정수를 입력받을 때는 버퍼를 지워주는 작업을 거쳐줘야 한다.
why? => 숫자 입력 메소드는 입력 후 개행 문자("\n")는 읽지 않는다. 'nextLine()'메소드는 이 남아 있는 개행 문자를 읽고 빈 문자열을 반환할 수 있기 때문에 'nextLine()'메소드로 스캐너의 버퍼를 지워준다.
코드는 아래의 예제를 통해 확인한다.
// 조건1. 나이를 모든 조건에 맞게 입력받을 때까지 반복
// 조건2. 0 이하의 숫자를 받을 시 안 되는 이유를 콘솔에 출력하고 다시 입력받기
// 조건3. 숫자가 아닌 값을 받을 시 안 되는 이류를 콘솔에 출력하고 다시 입력받기
// java.lang 패키지안의 오류 클래스를 제외한 모든 오류 클래스는 따로 import 해줘야함.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age;
while (true) {
try {
System.out.println("나이를 입력하세요.");
age = sc.nextInt();
sc.nextLine(); //버퍼 초기화
if (age < 1) {
System.out.println("나이는 1살 이상부터 입력 가능합니다. ");
continue;
}
System.out.println("입력받은 나이는 "+age+" 입니다. ");
} catch (InputMismatchException e) {
System.out.println("숫자를 입력해주세요.");
sc.nextLine(); // 버퍼 초기화
continue;
}
break;
}
}
}
final int PI = 3.14;class 사람 {
final void sayHi() {
System.out.println("hi");
}
}
class 홍길동 extends 사람 {
//void sayHi() { // 오류 : 오버라이딩 할 수 없음
// System.out.println("hi, i'm 홍길동");
//}
}
final class 사람 {}
// class 홍길동 extends 사람 {} // 오류 : 상속 못 함