본문 바로가기

Java/본격 Java 인터페이스

[Java] 자주사용되는 예외

- 자주 발생하는 예외
ArithmeticException : 연산불가(0으로 나누기)
ArrayIndexOutOfBoundsException : 배열의 인덱스 범위를 벗어난 예외
ClassCastException : 허용할 수 없는 형변환을 할 경우 발생하는 예외
NegativeArraySizeException : 배열의 크기를 음수로 지정할 때 발생
NullPointerException : 인스턴스가 null인데 사용하는 경우

.

.

예제

class RunTimeExceptionCase 
{
	public static void main(String[] args) 
	{
		try{
			int[] arr = new int[3];
			arr[-1] = 0;
		}catch (ArrayIndexOutOfBoundsException e){
			System.out.println(e.getMessage());
			System.out.println();
		}

		try{
			Object obj = new int[10];
			String str = (String)obj;
		}catch (ClassCastException e){
			System.out.println(e.getMessage());
			System.out.println();
		}

		try{
			int[] arr = new int[-10];
		}catch (NegativeArraySizeException e){
			System.out.println(e.getMessage());
			System.out.println();
		}

		try{
			String str = null;
			int len = str.length();
		}catch (NullPointerException e){
			System.out.println(e.getMessage());
			System.out.println();
		}
	}
}
728x90
반응형