Java

예외처리

hs_developer 2022. 6. 25. 19:11

예외 처리 방법에는 3가지가 있다.

1. try {} catch {} 사용
2. throws 사용
3. throw 사용

 

public class ExceptionTest {

	public void call(int j)
	{
		int[] i= {1, 2, 3};
		System.out.println("call value: " + i[j]);
	}

	public static void main(String[] args) {
		
		ExceptionTest et= new ExceptionTest();
		et.call(4); // 배열 크기를 초과하는 값을 호출, 에러 발생
	}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
	at ExceptionTest.call(ExceptionTest.java:6)
	at ExceptionTest.main(ExceptionTest.java:12)

 

 

 

1. try {} catch {}

public class ExceptionTest {

	public void call(int j)
	{
		try 
		{
			int[] i= {1, 2, 3};
			System.out.println("call value: " + i[j]);
		} 
		// 예외가 발생하면 출력
		catch(ArrayIndexOutOfBoundsException e)
		{
			System.out.println("배열 크기에 맞는 값을 입력하세요!");
			e.printStackTrace();
		}
		// Exception 여부와 상관없이 출력
		finally
		{
			System.out.println("해당 문장은 무조건 수행");
		}
	}

	public static void main(String[] args) {
		
		ExceptionTest et= new ExceptionTest();
		et.call(4);
	}
}

 

모든 예외를 처리하려면 Exception e 사용 한다.

 

printstacktrace() 메서드는 여러 내용을 출력하는데 사용 한다.

 

 

 

2. throws

public class ExceptionTest {

	public void call(int j) throws ArrayIndexOutOfBoundsException
	{
		try 
		{
			int[] i= {1, 2, 3};
			System.out.println("call value: " + i[j]);
		} 
		// 예외가 발생하면 출력
		catch(ArrayIndexOutOfBoundsException e)
		{
			System.out.println("배열 크기에 맞는 값을 입력하세요!");
			e.printStackTrace();
		}
		// Exception 여부와 상관없이 출력
		finally
		{
			System.out.println("해당 문장은 무조건 수행");
		}
	}

	public static void main(String[] args) {
		
		ExceptionTest et= new ExceptionTest();
		et.call(4);
	}
}

'Java' 카테고리의 다른 글

PrepareStatement  (0) 2022.07.04
다형성  (0) 2022.06.25
제네릭스  (0) 2022.06.25
인터페이스, 추상클래스  (0) 2022.06.25
this, super  (0) 2022.06.25