Errors in Programs

자바에서 발생할 수 있는 에러들

Run-time error

Run-time error은 errors와 exceptions으로 분류된다.

Erros and Exceptions

https://images.velog.io/images/tonyhan18/post/69923249-3253-490e-990d-8e55587c13b1/image.png

자바에서는 이러한 예외도 객체화 되어 있다. 그래서 위의 표와 같이 Throwa ble 클래스 밑에 Error과 Exception 그리고 RuntimeException이 존재

RuntimeException : ArrayIndexOutOfBoundsException, NullPointerException, ClassCastException, Arithmetic Exception 등이 존재

Exception : FileNotFoundException, ClassNotFoundException, DataFormatException

Exception Handling: try-catch

자바에서 에러를 처리하기 위해 try-catch블록을 사용하여 try 한다음 에러가 발생하면 catch에서 처리하여 프로그램을 계속 진행시키어 준다.

try {
	// 에러가 날 수 있는 것을 여기에 삽입
} catch (Exception1 e1) {
	// Exception1에 해당되는게 발생시 여기에서 처리
} catch (Exception2 e2) {
	// statements that will be executed when Exception2 occurs.
	try { } catch (Exception3 e3) { }
	// try-catch blocks can be nested. In that case, the parameters (e2 and e3) must be different.
} catch (ExceptionN eN) {
	// statements that will be executed when ExceptionN occurs.
}

Exception Handling: Example

public class Lecture {
	public static void main(String args[]) {
		int number = 100;
		int result = 0;
		for(int i=0; i<10; i++) {
			result = number / (int)(Math.random() * 10);
			System.out.println(result);
		}
	}
}

https://images.velog.io/images/tonyhan18/post/8942ece5-a221-4bdc-af86-35a11441c426/image.png