예외처리 try catch

jinkyung·2021년 1월 14일
0

JAVA

목록 보기
20/29

예외처리

if 조건을 준 것은 에러가 날 상황을 회피하는 것, 그것이 바로 예외처리이다.

package com.bit.day09.am;

public class Ex10 {

	public static void main(String[] args) {
		double su1=0.0/0.0;	
		if(Double.isNaN(su1)){			
			su1=0.0;
		}
		System.out.println(su1+1);			//if 조건이 없다면 NaN 출력
	}
}

try catch문

예외처리는 고치는 개념이 아니다. 그럴 수 있는 상황 자체를 회피하는 것이다.

이를 활용하는 것은 case by case이기 때문에 직접 그러한 상황과 부딪혀서 경험쌓는 수밖에없다..

package com.bit.day09.am;

public class Ex10 {

	public static void main(String[] args) {
		int[] arr1={1,3,5};
		try{
			System.out.println(arr1[3]+1); 		//에러발생			
		}catch(ArrayIndexOutOfBoundsException e){	//예외처리 (e는 상관없는 변수명)
			System.out.println("인덱스 똑바로처리해");	//대안
		}
	}
}

package com.bit.day09.am;

public class Ex11 {

	public static void main(String[] args) {
		int su=0;
		try{
		su=Integer.parseInt("a");			//문자열에 들어간 문자는 처리 못한다.
		} 
          //에러가 생기면 catch블럭으로 넘어와서 확인
          catch(java.lang.NumberFormatException e) {		
			System.out.println("error");
		}		
		System.out.println(su+1);   	//try에서 문제가 없으면 여기로 넘어와 실행된다.
	}
}

try의 범위에 따라 결과가 달라진다.

package com.bit.day09.am;

public class Ex12 {
	public static void main(String[] args) {
			
		int[] arr={1,3,5,7};
		
		for(int i=0; i<10; i++){
			try{
			System.out.println(arr[i]);
			}
		catch(java.lang.ArrayIndexOutOfBoundsException e){	
				System.out.println("에러처리");	//에러처리 6번 출력 
			}
		}
	}
}
package com.bit.day09.am;

public class Ex12 {
	public static void main(String[] args) {
			
		int[] arr={1,3,5,7};
		
		try{
		for(int i=0; i<10; i++){
			System.out.println(arr[i]);
			}
		}catch(java.lang.ArrayIndexOutOfBoundsException e){     //에러처리 1번 출력. 에러가 나면 내려온다
				System.out.println("에러처리");
			}
		}
	}

컴퓨터 입장에서는 에러가 날지 안날지는 돌려봐야 아는 것이기 때문에 둘다 초기화 해줘야한다.

try 안에서는 작업을 하거나, 초기화는 안하는 것이 좋다. (a may not have been initialized)

package com.bit.day09.am;

public class Ex12 {
	public static void main(String[] args) {
			
		int[] arr={1,3,5,7};
		int a;
		
		try{                      //a의 초기화를 둘 다 시켜줘야 오류가 뜨지 않는다.
		for(int i=0; i<4; i++){
			System.out.println(arr[i]);
			}
			a=12;
		}catch(ArrayIndexOutOfBoundsException e){ 
				System.out.println("에러처리");
			a=1;
		}
		System.out.println(a);
		}
	}

다중 catch

package com.bit.day09.am;

public class Ex13 {

	public static void main(String[] args) {

//다중 catch
		
		String[] arr = { "1", "2", "3", "a" };

		for (int i = 0; i < 5; i++) {
	
			try {
				System.out.println(Integer.parseInt(arr[i]));

			} catch (NumberFormatException e) {
				System.out.println("숫자가 아님");
				
			} catch (ArrayIndexOutOfBoundsException e) {
				System.out.println("인덱스 많음");
			}
		}
	}
}

> ### Exception Class

:모든 exception의 최상위 클래스는 exception 클래스이다.

두 에러 모두 exception클래스를 상속받기 때문에 다형성에 따라서 처리할 수 있다.

public class Ex13 {

	public static void main(String[] args) {


		
String[] arr = { "1", "2", "3", "a" };
for (int i = 0; i < 5; i++) {
	
	try {
		System.out.println(Integer.parseInt(arr[i]));
	}catch(Exception e){
		System.out.println("에러처리");	 //위의 두가지 에러 모두 처리하여 2번 출력
	}	

주의할 점

package com.bit.day09.am;

public class Ex13 {

	public static void main(String[] args) {

//다중 catch
		
		String[] arr = { "1", "2", "3", "a" };

		for (int i = 0; i < 5; i++) {
	
				try {
					System.out.println(Integer.parseInt(arr[i]));
				}catch(Exception e){				//여기서 다 처리해버리므로 밑의 캐치문은 실행할 수 없다. 그래서 오류
					System.out.println("에러처리");	 									
			} catch (NumberFormatException e) {
				System.out.println("숫자가 아님");
			} catch (ArrayIndexOutOfBoundsException e) {
				System.out.println("인덱스 많음");
			}
		}
	}
}

package com.bit.day09.am;

public class Ex13 {

	public static void main(String[] args) {

//다중 catch
		
		String[] arr = { "1", "2", "3", "a" };

		for (int i = 0; i < 5; i++) {
	
				try {
					System.out.println(Integer.parseInt(arr[i]));									
			} catch (NumberFormatException e) {
				System.out.println("숫자가 아님");
			} catch (ArrayIndexOutOfBoundsException e) {
				System.out.println("인덱스 많음");
			}catch(Exception e){				//이것은 가능.
				System.out.println("에러처리");	 
			}
		}
	}
}

0개의 댓글

관련 채용 정보