대표적인 예외의 종류

    RuntimeException

    1. ArithmeticException

    - 산술 연산에서 예외 조건이 발생했을 때 발생

    class ArithmeticExceptionPractice {
    	public static void main(String args[]) {
        	try {
            	
                int a = 10;
                int b = 0;
                
                int c = a / b;
                
           } catch (ArithmeticException e) {
           		
                System.out.println("0으로 나눌 수 없습니다.");
                
           }
        }
    }

    2. ArrayIndexOutOfBoundsException

    - 잘못된 인덱스로 Array에 액세스했을 때 발생

    class ArrayIndexOutOfBoundsPractice {
    	public static void main(String args[]) {
        	try {
            	
                int a[] = new int[5];
                a[6] = 10;
                
           } catch (ArrayIndexOutOfBoundsException e) {
           		
                System.out.println("인덱스의 수에 접근할 수 없습니다.");
                
           }
        }
    }

    3. NullPointerException

    null 객체의 멤버를 참조할 때 발생

    class NullPointerExceptionPractice {
    	public static void main(String args[]) {
        	try {
            	
                String a = null;
                String b = a.chatAt(2);
                
           } catch (NullPointerException e) {
           		
                System.out.println("해당 객체는 null값입니다.");
                
           }
        }
    }

    4. NumberFormatException

    숫자로 변환될 수 없는 문자열이 있는 경우 발생

    class NumberFormatExceptionPractice {
    	public static void main(String args[]) {
        
        String a = "2chocho2";
        	try {
            	
                int value = Integer.parseInt(a);
                
           } catch (NullPointerException e) {
           		
                System.out.println(a+ "는 숫자로 변환할 수 없습니다.");
                
           }
        }
    }

    'JAVA' 카테고리의 다른 글

    예외  (0) 2023.04.02
    인터페이스  (0) 2023.04.02
    상속  (0) 2023.04.02
    접근지정자 - Abstract  (0) 2023.04.02
    접근지정자 - Final  (0) 2023.04.02

    댓글