쌍용교육(JAVA)/JAVA

쌍용교육 -JAVA 수업 12~13일차 Exception예외

구 승 2024. 4. 11. 22:39
package kr.s26.exception;

public class ExceptionMain01 {
	public static void main(String[] args) {
		int[] array = {10,20,30};
		/*
		 * 테스트용으로 없는 인덱스 3을 호춣해서 예외를 발생시킴.
		 * 예외가 발생하면 예외가 발생한 지점에서 프로그램이 강제로 종료됨.
		 */
		for(int i=0; i<=array.length; i++) {
			/*
			 * 예외가 발생하고 프로그램이 멈춤
			 * ****예외가 발생하면 예외 정보를 담고 있는 예외 객체가 생성되고 예외 문구가 콘솔에 출력됨****
			 */
			System.out.println("array ["+i+"] : "+ array[i]);
		}
		System.out.println("프로그램 끝!!!");
	}
}
array [0] : 10
array [1] : 20
array [2] : 30
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
	at kr.s26.exception.ExceptionMain01.main(ExceptionMain01.java:15)

package kr.s26.exception;

import java.lang.reflect.Array;

public class ExceptionMain02 {
	public static void main(String[] args) {
		int[] array = {10,20,30};
		for(int i = 0; i<= array.length;i++) {
			//예외처리:예외가 발생해도 정상 종료될 수 있도록 프로그램적으로 처리하는 것을 말함.
			try {
				//예외가 발생할 가능성이 있는 코드를 명시
				//만약 예외가 발생하면 예외가 발생한 코드의 실행을 멈추고 catch블럭으로 이동
				System.out.println("array ["+i+"] : "+ array[i]);
			}catch(ArrayIndexOutOfBoundsException e) { //e 는 예외 객체
				System.out.println("없는 인덱스 호출");
			}
		}//end of for
		System.out.println("프로그램 끝!!!");
	}
}
array [0] : 10
array [1] : 20
array [2] : 30
없는 인덱스 호출
프로그램 끝!!!

package kr.s26.exception;

public class ExceptionMain03 {
	public static void main(String[] args) {
		int var = 50;
		//예외처리
		//다중 catch문 : 예외가 발생하면 예외 객체가 전달되는 catch블럭으로 이동해서 수행문을 실행
		//수행문을 실행
		try {
			int data = Integer.parseInt(args[0]);//.parseInt() -> String을 Int로
			System.out.println(var/data);
			/*
			 * (주의) 다중 catch문을 사용할 때 Exception과 하위 예외 클래스를 동시에 명시할 때
			 * 하위 예외 클래스를 먼저 명시하고 가장 뒤에 Exception을 명시해야 동작상의 문제가 발생하지 않음.
			 */
			//하위 예외 클래스들
		}catch(ArrayIndexOutOfBoundsException e) {
			System.out.println("입력한 데이터가 없습니다.");
		}catch(NumberFormatException e) {
			System.out.println("숫자가 아닙니다.");
		}catch(ArithmeticException e ) {
			System.out.println("0으로 나눌 수 없습니다.");
		}catch(Exception e) { // 위에 catch(예외 클래스들)들 위에 쓰면 에러가 난다. Exception은 무조건 맨아래에 써야됨.   
			System.out.println("나머지 예외는 여기로~");
		}
		
		System.out.println("프로그램 종료!!");
	}
}
//Run -> Run Configurations ->argument에서 값 입력
입력한 데이터가 없습니다.
프로그램 종료!!

package kr.s26.exception;

public class ExceptionMain04 {
	public static void main(String[] args) {
		/*
		 * <멀티 catch>
		 * 하나의 catch블럭에서 여러개의 예외를 처리할 수 있도록
		 * 예상되는 예외 클래스를 여러 개 명시하는 방식
		 */
		try {
			int value1 = Integer.parseInt(args[0]);
			int value2 = Integer.parseInt(args[1]);
			int result = value1 + value2;
			System.out.println(value1 + "+" + value2 + "=" + result);
		}catch(ArrayIndexOutOfBoundsException | NumberFormatException e) { // ||가 아닌 | 1개로 or의 개념을 사용한다.
			//System.out.println("실행 매개값의 수가 부족하거나 숫자를 변환할 수 없습니다.");
			
			//예외정보제공
			//System.out.println(e.toString());
			//e/printStackTrace();
			
			if(e instanceof ArrayIndexOutOfBoundsException) {
				System.out.println("입력한 데이터가 없습니다.");
				
			}else if (e instanceof NumberFormatException) {
				System.out.println("숫자가 아닙니다.");
			}
			
			
		}catch(Exception e) {
			System.out.println("알 수 없는 예외 발생");
		}
	}
}

java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
	at kr.s26.exception.ExceptionMain04.main(ExceptionMain04.java:11)

아마 args의 값을 넣지 않아서 에러가 나는듯.
package kr.s26.exception;

public class ExceptionMain05 {
	public static void main(String[] args) {
		//try~catch~finally
		//finally 영역은 예외가 발생하든 발행하지 않든 무조건 수행하는 부분
		System.out.println("===예외가 발생하지 않는 경우===");
		try {
			System.out.println(1);
			System.out.println(2);
		}catch(Exception e){
			System.out.println(3);
		}finally {
			System.out.println(4);
		}
		System.out.println("-----------------");
		System.out.println("=======예외가 발생하는 경우========");
		try {
			System.out.println("1");
			System.out.println(10/0);
			System.out.println("2");
		}catch(Exception e) {
			System.out.println("3");
		}finally {
			System.out.println("4");
		}
	}	
}
===예외가 발생하지 않는 경우===
1
2
4
-----------------
=======예외가 발생하는 경우========
1
3
4

package kr.s26.exception;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class ExceptionMain06 {
	/*
	 * throws 예약어의 사용
	 * 메서드에 throws 예외클래스를 명시하면 메서드내에 try~catch블럭을 생략하고 
	 * 예외가 발생하면 예외를 임시 보관하고 메서드를 호출하는 곳에
	 * try~catch블럭이 있을 경우 그곳으로 예외를 양도함.
	 */
						//()와 {} 사이에 throws를 입력해야됨. IOException는 필수로 입력해야하지만 NumberFormatException은 런타임시에만 진행되기 떄문에 필수 입력은 아니다. 
	public void printData()throws IOException, NumberFormatException {//예외를 이곳에서 임시 보관해준다.
							//throws IOException, NumberFormatException를 쓰지 않으면 아래에 br.readLine()의 빨간밑줄이 생긴다.
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.print("단 입력:");

		//String -> int //BufferedReader는 String으로 받기 때문에 int로 바꿔야된다(?)
		int dan = Integer.parseInt(br.readLine());//한 라인에 입력한 데이터를 반환 //br.readLine();는 try catch로 감싸주지않으면 에러가남
		System.out.println(dan + "단");
		System.out.println("---------------------------");
		for (int i =1; i<=9 ;i++) {
			System.out.println(dan+"*"+ i + "=" + dan*i);
		}

	}

	public static void main(String[] args) {
		ExceptionMain06 em = new ExceptionMain06();
		try {
			em.printData();
		}catch(IOException e) {
			System.out.println("입력시 오류 실행");
		}catch(NumberFormatException e) {
			System.out.println("숫자가 아닙니다.");
		}
	}
}

단 입력:2
2단
---------------------------
2*1=2
2*2=4
2*3=6
2*4=8
2*5=10
2*6=12
2*7=14
2*8=16
2*9=18

package kr.s26.exception;

public class ExceptionMain07 {
	public void methodA(String[] n) throws Exception {
		if(n.length >0) {//데이터 입력 O
			for(String s :n) {
				System.out.println(s);
			}
		}else {//데이터 입력 X
			//예외를 인위적으로 발생시킴
			throw new Exception("배열의 요소가 없습니다.");//*************	
		}
	}
	public static void main(String[] args) {
		ExceptionMain07 em = new ExceptionMain07();
		try {
			em.methodA(args);
		}catch(Exception e) {
			//예외문구 출력
			//System.out.println(e.toString());//결과:java.lang.Exception: 배열의 요소가 없습니다.
			System.out.println(e.getMessage());//메시지만 읽어와라//결과:배열의 요소가 없습니다.
		}
	}
}
배열의 요소가 없습니다.

package kr.s26.exception;

import java.util.Scanner;

//사용자 정의 예외 클래스
class NegativeNumberUseException extends Exception{
	public NegativeNumberUseException(String str) {
		super(str);
	}
}
public class ExceptionMain08 {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.print("0이상만 입력:");
		try {
			int a = input.nextInt();
			if(a>=0) {
				System.out.println("입력한 숫자 : "+ a);
			}else {//음수 입력
				//사용자 정의 예외 클래스에 예외 문구를 저장해서
				//객체로 생성해서 예외를 발생시킴.
				throw new NegativeNumberUseException("음수를 사용할 수 없습니다.");
			}
		}catch(NegativeNumberUseException e) {
			System.out.println(e.getMessage());
		}catch(Exception e) {
			System.out.println("예외 발생");
		}finally {
			if(input != null) input.close();
		}
	}
}
0이상만 입력:5
입력한 숫자 : 5

0이상만 입력:-1
음수를 사용할 수 없습니다.