○ Exception
- Exception : 자바 클래스 실행(run)시 발생하는 에러
- exception 예시
① ArrayIndexOutOfBoundsException
int[] num = new int[3];
num[5]=2; //ArrayIndexOutOfBoundsException
② NumberFormatException
int no=Integer.parseInt("KOREA"); //NumberFormatException
③ NullPointerException
Integer inte=null;
System.out.println(5/inte); //NullPointerException
④ ArithmeticException
System.out.println(1/0); //ArithmeticException
○ 예외처리
- Exception이 발생하면 프로그램은 정상적으로 종료되지 않음
System.out.println(1);
System.out.println(3/0); //ArithmeticException발생, 프로그램이 정상적으로 종료되지 않음
System.out.println(5); //출력되지 않음
System.out.println("END"); //출력되지 않음
- Exception이 발생하더라도 정상적으로 프로그램은 종료시키기 위해 예외처리가 필요
- 형식) try { 예외 발생이 예상되는 코드 } catch(Exception e) { 예외발생시 처리할 코드 }
try {
System.out.println(1);
System.out.println(3/0); //ArithmeticException발생
System.out.println(5); //출력되지 않음
}catch(ArithmeticException e) {
System.out.println(e); //출력됨(java.lang.ArithmeticException: / by zero)
}
System.out.println("END"); //출력됨
- 다중 catch문
catch(NumberFormatException e) {
System.out.println(e);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}catch(NullPointerException e) {
System.out.println(e);
}
System.out.println("END");
○ Exception 클래스
- 모든 예외 발생의 조상 클래스
- 서브클래스로 exception 목록이 모두 들어가 있음
- Exception클래스로 catch문 처리 가능
try {
int a=2/0;
int b=Integer.parseInt("KOREA");
int[] num=new int[3];
num[5]=7;
}catch(Exception e) {
System.out.println(e);
}
System.out.println("END");
○ finally문
- 예외가 발생하든 발생하지 않든 무조건 실행
- 형식) try { 예외 발생이 예상되는 코드 } catch(Exception e) { 예외발생시 처리할 코드 } finally { 항상 실행할 코드 }
try {
System.out.println("OPEN");
System.out.println(1/0);
}catch (Exception e) {
System.out.println(e);
}finally {
System.out.println("CLOSE");
}
System.out.println("END");
○ throws를 이용한 예외처리
- 메소드(함수) 호출 시 예외처리를 한꺼번에 모아서 처리
- 메소드에만 적용할 수 있는 명령어, 메소드 작성시 함수명 옆에 붙여줌
class Test {
public void view() throws Exception {
int a=3/0;
System.out.println(a);
}//view() end
public void disp() throws NullPointerException, NumberFormatException {
int a= Integer.parseInt("KOREA");
System.out.println(a);
}//disp() end
}//class end
public class Test02_throws {
public static void main(String[] args) {
try {
Test test = new Test();
test.disp();
test.view();
}catch (Exception e) {
System.out.println(e);
}
}//main() end
}//class end
- 참고) throws처럼 메소드에만 적용할 수 있는 명령어 synchronized
→ OS가 개입해서 문제가 발생하지 않도록 조정하는 기법
public synchronized void login() {}
'Backend > JAVA_Basic' 카테고리의 다른 글
24. JAVA, Thread 클래스 (Runnable 인터페이스) (0) | 2022.06.08 |
---|---|
23. Java Collection Framework (List, Set, Map, generic) (0) | 2022.06.07 |
21. JAVA, 추상화 (추상 클래스, 추상 메소드, 인터페이스, 익명내부객체) (0) | 2022.06.05 |
20. JAVA, 다형성(polymorphism) (0) | 2022.06.04 |
19. JAVA, 상속(inheritance, override, super, Object 클래스) (0) | 2022.06.03 |
댓글