JAVA

[JAVA]예외처리

로돌씨 2024. 2. 22. 19:17

예외처리(Exception)

오류의 종류

  • 컴파일 에러 : 프로그램의 실행을 막는 소스 상의 문법에러 ( 빨간 줄 )
  • 런타임 에러 : 입력값이틀렸거나 배열의 인덱스범위를 벗어났거나 계산식의 오류 등 주로 if문 사용으로 에러처리
  • 시스템 에러 : 컴퓨터 오작동으로 인한 에러

RuntimeException

import java.io.File;
import java.util.Scanner;

public class RunExceptionTest {
	Scanner sc = new Scanner(System.in);

	public void test1() {
		// RuntimeException 중에서ArithmeticException확인
		int ran = 0; // 랜덤값의 변수
		int res = 0; // 결과 값 변수

		
		/*if로 처리 
		while (true) {
			System.out.print("정수 하나 입력 : ");
			int inputNum = sc.nextInt();
			// 0을 입력했을때 에러남 -> 해결해보자
			if (inputNum == 0) {
				System.out.println("0이 아닌 값을 입력하세요 ."); // 이걸 추가해줘서 0을 입력했을때 에러가아닌 이메세지가 뜨도록 설정 
				//if문을 이용한 간단 에러해결
			} else {
				if (inputNum == 11) {
					System.out.println("종료");
					break;
				}
				ran = (int) (Math.random() * 10) + 1; // 랜덤은 1부터 10까지의 수
				res = ran / inputNum; // 랜덤을 인풋넘으로 나
				if (res == 3) {
					System.out.println("나눴을때에 나머지가 3입니다. 맞췄습니다.");
					break;

				}
			} // 0은 나누지못하기때문에  생긴 에러를 if로 해결하는 방법 

		}*/
		//2.try catch로 처리
		
		try { 
			System.out.print("정수 하나 입력");
			int inputNum = sc.nextInt();
			ran = (int)(Math.random()*10)+1;
			res = ran/inputNum;
			System.out.printf("%d /%d = %d\n", ran , inputNum,res);
			//예외가 들어갈 코드는 꼭 들어가야함
		}catch(ArithmeticException e){ // 에러형식을 잘넣어야 처리가 가능
			e.printStackTrace(); //에러메세지를 출력하겠다.
			System.out.println("Exception발생");
			System.out.println(e.getMessage()); //에러 이유 출력
		}
		
		}
		public void test2() {
			try {
				/*
			//ClasscastException
			Object obj = 'a'; //wrapper character
			System.out.println(obj);
			//String str = (String)obj; //강제로 스트링으로 형변환을해서 에러가 일어남 
			System.out.println("oo"); //(str) 넣었다가 oo로 바꾸면 캐치 실행안되고 바로 파이널리로 감 
			*/
				
			//ArrayIndexOutOfBoundsException
			/*int [] arr = new int[1];
			arr[0] = 1 ;
			arr[1] = 2 ; // 배열범위를 넘어간 에러 
			*/
				//NullPointerException
				String str = null;
				int length = str.length(); //null인데 길이를 재려함
				
			} catch(ClassCastException e) {
				e.printStackTrace(); //에러메세지를 출력하겠다
				System.out.println("형식이 잘못됐어");
			}catch(ArrayIndexOutOfBoundsException e){
				System.out.println("이건 배열범위를 넘어가서 발생한 에러야");
				System.out.println(e.getMessage());
			}catch(NullPointerException e){
				System.out.println("null인데 길이를 어떻게 재??");
				System.out.println(e.getMessage());
			}finally {
				System.out.println("어쨌든 끝!");
			}
			

				
			}
		}

 

Throw

 import java.io.IOException;

public class Run {

	public static void main(String[] args) /*throws IOException*/ {
		try {							// 6. 메인에서스로우하지않고 트라이캐치로 처리함 
			methodA();
		} catch (IOException e) {
			System.out.print("main()에서 처리");
		} 

	}

	public static void methodA() throws IOException{
		methodB(); // 5. 계속 넘겨줌 
	}

	public static void methodB() throws IOException {
		methodC(); // 4.떠넘겨져서 에러가 뜸 
	}
		

	public static void methodC() throws IOException { 
	/*	try {
		throw new IOException(); //1. 예외처리 하라고 에러뜸
	    }catch(IOException e) {
		e.printStackTrace();
		}
		*/ //2.예외처리 추가
	 //3.대신사용 메소드 옆에 throws IOException 추가
		throw new IOException(); 
	}
}출력값:
main()에서 처리

 

MyExceptionClass

 

예외 클래스 생성

public class MyException extends Exception /*예외클래스 생성*/ {
	public MyException() { //기본생성자 
		System.out.println("내가만든 예외클래스 ~");
	}
	public MyException(String msg) { //매개변수 생성자
		super(msg); //매개변수 생성 
	}
}

 

출력

import java.util.Scanner;

public class Run {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("정수 하나 입력: ");
		try {
		checkNum(sc.nextInt());
		}catch(MyException e) {
			e.printStackTrace();
		System.out.println(e.getMessage());
		} // 10보다크면 정상 출력 /10보다 작으면마이익셉션
		//(예외클래스)으로 넘어감
	}

	public static void checkNum(int num) throws MyException {
		if (num < 10) {
			//MyException me = new MyException();
			//throw me; //10보다 작으면 마이익셉션으로 쓰로우하겠다 .
			throw new MyException(num + "은 10보다 작은수 ");
			//에러 메세지옆에 이 메세지가 뜸 
		} else {
			System.out.println(num + "은10보다 크거나같다.");
		}
	}

}출력값:
정수 하나 입력: 11
11은10보다 크거나같다.

,
정수 하나 입력: 1
com.chap03_myException.MyException: 1은 10보다 작은수 
	at com.chap03_myException.Run.checkNum(Run.java:23)
	at com.chap03_myException.Run.main(Run.java:11)
1은 10보다 작은수

'JAVA' 카테고리의 다른 글

[JAVA]입출력( I / O ) #2  (1) 2024.02.26
[JAVA]입출력( I / O )  (0) 2024.02.22
[JAVA]객체#3  (0) 2024.02.21
[JAVA]객체#2  (0) 2024.02.20
[JAVA]객체지향 프로그래밍  (0) 2024.02.19