YSHUSH

Exception 본문

Coding/Java

Exception

코딩; 2021. 12. 14. 02:02

 

˙ Exception : 예외 != 에러
     int number <- 'A' == 65
  
  예) 
   number    ->    char
   array     ->    범위초과 [5]    ->     0 ~ 4    ::    [5]
   class    ->    없음
   file    ->    없음 (그 위치에없는 것 - 외부적인 요인)
  

형식

		  	try {
		  		
		  		예외가 발생될 가능성이 있는 코드
		  		
		  	} catch ( 예외클래스1 e ) {	<- ex) number
		  		예외 클래스 메시지 출력
		  	} catch ( 예외클래스2 e ) {	<- ex) bound
		  		예외 클래스 메시지 출력
		  	}	
		  		.
		  		.	// <- 계속 추가 가능
		  		.
		  		:
		  	finally {
            
		  		무조건 실행!
		  		뒤처리
		  	}
		  		
		 	// 개발자를 위한 코드 == error 일수도 있으나 error가 아닐수도 있다.
		 		
		 	함수 안에서 발생할 경우
		 	static void method() throws 예외클래스 {
		 		함수 안에서 예외가 발생될 경우
		 	}
		 
		 	// 예외는 일반 클래스에서 발생하는 경우와 함수 안에서 발생하는 경우 두가지가 있다.

			// exception이 발생했을 경우 catch해서 처리를 해줘야 할 때 쓴다. (후처리할때)
			// 문제가 발생했을 때 대처하기 위해서 쓰임
public class MainClass {
	public static void main(String[] args) {
    
	int[] array = {1, 2, 3};
		
		System.out.println("start");
		
		try {
		
			for (int i = 0; i < 4; i++) {
				System.out.println(array[i]);
			}
			
			System.out.println("process");
			
		} catch (ArrayIndexOutOfBoundsException e) {
		//	System.out.println("배열의 범위 초과");
			e.printStackTrace();	// .printStackTrace() => exception 메세지를 출력해줌
			
		//	return;		// main이 void이므로 return값으로
						// 이 밑의 문장은 실행하지 않으나, finally는 실행됨!
		} catch (ArithmeticException e) {
			e.printStackTrace();
		} finally {		// finally는 무조건 실행!
			System.out.println("finally 부분");
		}
		// error는 동작이 에러가 남! exception 과 error의 다른 점을 알아야함
		System.out.println("end");
			
		
		method();
		
		try {
		objectCall();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			
		}
	}
		// Exception만 쓰면 통합 exception 처리로 두개의 exception도 처리할 수 있다. 
	static void method() throws IndexOutOfBoundsException {		// IndexOutOfBoundsException => 이 함수에서 포괄적으로 문제가 발생할 수 있다
		int num[] = {1, 2, 3};
		for (int i = 0; i < 4; i++) {
			System.out.println(num[i]);
		}
	}
	
	static void objectCall() throws ClassNotFoundException {
		Class.forName("MyClass");	// 원래는 myclass가 있어야하는데 익셉션처리
	}					// throws ClassNotFoundException으로
						// 예외처리를 해줄 수 있음.
}						// forName 함수는 throw and catch가 필수! - f3눌러서 확인

 

Exception의 대표적인 5가지 상황들

		// NullPointerException : 동적 할당이 안된경우
		String str = null;
		
		try {
			System.out.println(str.length());
		} catch(NullPointerException e) {
			e.printStackTrace();
		//	System.out.println("str은 할당되지 않았습니다");
		}	// 이 후에 while문을 추가해서 다시 string을 할당해라 라고 할 수 있다.	
		
		
		// ArrayIndexOutOfBoundsException : 배열 범위를 초과한 경우
		int[] array = {1, 2, 3};
		
		try {
			array[2] = 'A';
		} catch (ArrayIndexOutOfBoundsException e) {
			e.printStackTrace();
		}
		
		
		// FileNotFoundException : 불러오려는 파일이 없는경우
		File file = new File("d:\\xxx");
		FileInputStream is;
		
		try {
			is = new FileInputStream(file);
		} catch(FileNotFoundException e) {
			e.printStackTrace();
		}
		
		
		// StringIndexOutOfBoundsException : 문자열의 길이가 넘어간 경우
		String str1 = "java";
		
		try {
			str1.charAt(4);
		} catch (StringIndexOutOfBoundsException e) {
			e.printStackTrace();
		}
		
		
		// NumberFormatException : 숫자가 아닌 경우
		try {	
			int number = Integer.parseInt("12a");
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
 	}
}	
	// ~~~~~Exception을 그냥 Exception만 써서 바꿔도 된다. but 정확한게 좋긴함

'Coding > Java' 카테고리의 다른 글

File reader  (0) 2021.12.14
File I/O  (0) 2021.12.14
Overload  (0) 2021.12.14
Method1  (0) 2021.12.12
문자 판별기  (0) 2021.12.09