발생한 예외. 내가 직접 조진다
try블럭 안에 예외 발생 가능성 문장을 넣고, catch 안에 발생 시 처리할 문장을 넣으믄 됨.
class ExceptionEx1 {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2);
try {
System.out.println(3);
System.out.println(0/0); // 예외 발생
System.out.println(4);
} catch (ArithmeticException ae) {
System.out.println("오류당");
} catch (Exception e) {
System.out.println("실행 안되자너");
}
}
}
//멀티 catch 예시
class test {
try {
...
} catch (ExceptionA | ExceptionB) {
if ( e instanceof ExceptionA) {
ExceptionA e1 = (ExceptionA) e;
e1.methodA();
} else {
...
}
}
}
- new를 이용해 발생시키려는 예외 클래스 객체 생성
Exception e = new Exception("고의다");- throw를 이용해 예외 발생
throw e;
class ExceptionEx0 {
public static void main(String[] args) {
try {
throw new Exception("고의맨");
} catch (Exception e) {
Systm.out.println("에러 메세지 : " + e.getMessage());
e.printStackTrace();
}
}
}
나 말고 나 부른넘이 처리해 줄겁니다..
메서드 호출 시 어떤 예외가 발생할 수 있다고 미리 알리기
+) 예외 되던지기
이새기 점점 대충쓰는거같은데 아닙니다 아니애요 나애대한 공격을멈처줘요
예외 발생 여부에 상관없이 실행되도록. try블럭 안에 return문이 있어서 try블럭을 벗어나야 할 때도 finally블럭은 실행된다.
예시는 깃허브를 보세요
- 여러 예외를 하나로 묶어서 다루기 위해
- checked 예외 -> unchecked 예외로 변경 시
Throwable initCause(Throwable cause) //지정한 예외를 원인예외로 등록
Throwable getCause() // 원인 예외를 반환
static void startInstall() throws SpaceException, MemoryException {
if (!enoughSpace())
throw new SpaceException("설치할 공간 부족");
if (!enoughMemory())
throw new MemoryException("메모리 부족");
}
아래와 같이 고쳐보자
static void startinstall() throw SpaceException {
if (!enoughSpace())
throw new SpaceException("설치할 공간 부족");
if (!enoughMemory())
throw new RuntimeException(new MemoryException("메모리 부족"));
}
checked 예외인 MemoryException을 RuntimeException으로 감싸 unchecked 예외로 전환시켰다.
진짜 돌아버린 사람이 쓴 글 같아요
재밌게 잘 보고갑니다 !