Exception : Check의 주체는 컴파일러
문법에 맞지 않게 작성된 코드 : 실행이 안됨
실행 중에 발생한 오류 (오동작이나 결과에 악영향을 미칠 수 있음)
ex)
예외 발생 -> 자바 플랫폼 인지 -> 응용프로그램에서 전달 -> 응용프로그램이 예외를 처리하지 않으면 강제 종료
try{
예외가 발생할 가능성이 있는 실행문 (try 블록)
}
catch(처리할 예외 타입 선언){ // catch 블록은 여러개 올 수 있음
예외 처리문(catch 블록)
finally{ // 예외 처리 때문에 추가된 코드
예외 발생 여부와 상관없이 무조건 실행되는 문장
}
속도는 조금 느려 실시간 반응 프로그램을 만드는데는 사용하지 않음
import java.util.Scanner;
public class DevideByZeroHandling {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.print("나뉨수를 입력하시오:");
int dividend = scanner.nextInt(); // 나뉨수 입력
System.out.print("나눗수를 입력하시오:");
int divisor = scanner.nextInt(); // 나눗수 입력
try{
System.out.println(dividend + "를 " + divisor +
"로 나누면 몫은 " + dividend/divisor + "입니다.");
break; // 정상적인 나누기 완료 후 while 벗어나기
}
// ArithmeticException 예외 처리 코드
catch(ArithmeticException e) { // class 명 = ArithmeticException
// e.printStacktrace() 자주 사용됨 : 예외 발생 함수부터 trace를 출력
System.out.println("0으로 나눌 수 없습니다! 다시 입력하세요");
}
}
scanner.close();
}
}
public class ArrayException {
public static void main (String[] args) {
int[] intArray = new int[5];
intArray[0] = 0;
try {
for (int i=0; i<5; i++) {
intArray[i+1] = i+1 + intArray[i];
System.out.println("intArray["+i+"]"+"="+intArray[i]);
}
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("배열의 인덱스가 범위를 벗어났습니다.");
}
}
}
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputException {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("정수 3개를 입력하세요");
int sum=0, n=0;
for(int i=0; i<3; i++) {
System.out.print(i+">>");
try {
n = scanner.nextInt(); // 정수 입력 -> 사용자가 문자를 입력하면 예외 발생
}
catch(InputMismatchException e) {
System.out.println("정수가 아닙니다. 다시 입력하세요!");
scanner.next(); // 입력 스트림에 있는 정수가 아닌 토큰을 버린다.
i--;// 인덱스가 증가하지 않도록 미리 감소
continue; // 다음 루프
}
sum += n; // 합하기
}
System.out.println("합은 " + sum);
scanner.close();
}
}
public class NumException {
public static void main (String[] args) {
String[] stringNumber = {"23", "12", "3.141592", "998"};
int i=0;
try {
for (i=0; i<stringNumber.length; i++){
int j = Integer.parseInt(stringNumber[i]);
//“3.141592”를 정수로 변환할 때 NumberFormatException 예외 발생
// 사후처리(예외처리)가 아닌 if문으로 예방하려 하면 너무 복잡, 따질게 많음
System.out.println("숫자로 변환된 값은 " + j);
}
}
catch (NumberFormatException e) {
System.out.println(stringNumber[i] + "는 정수로 변환할 수 없습니다.");
}
}
}
명품 Java Programming(황기태, 김효수 저)
Yes, I agree with you completely. You can't have a successful online presence for your organisation without top quality content, which is why technical writing free games is so crucial.
nice idle breakout