JAVA/Basic

[스터디할래? Java 09]예외처리

[스터디할래? Java] 목차

 

이글은 백기선님 스터디 할래? 스터디를 뒤늦게 따라간 기록입니다.

스터디할래 링크 >> https://github.com/whiteship/live-study

이필기를 시작으로 공부했습니다 >>  https://www.notion.so/3565a9689f714638af34125cbb8abbe8

여기 없는내용은 스터디 할래 강의 내용 혹은 제가 java Doc보고작성하거나 예제를 만들어 추가했습니다.

그외는 같이 출처가 써있습니다. 

 

 

자바제공하는 예외 계층구조 Object <- Throwable <- Error :치명적 시스템오류 해결불가. 
                            <- Exception <- RuntimeException : unchecked Exception
                                              <- RE 아닌 Exception : checked Exception
Exception vs Error 오류 :Error : 시스템의 비정상적인 상황이 생겼을때. 시스템레벨, 심각한수준 오류.  예측불가
                개발자가 상속받지도, 사용할필요 없음. 
예외 :Exception : 개발자가 구현한로직에서 발생, 미리 예측 처리
RuntimeException vs RE가 아닌 Exception RuntimeException : Unchecked Exception
: 예외처리 하지 않아도 됨.
ex) IOException, SQLException

RE 아닌 Exception : checked Exception
: 반드시 예외 처리. 
NullPointException, IllegalArgumentException

https://cheese10yun.github.io/checked-exception/
throw vs throws throws 현재 메서드에서 호출한 "상위 메서드로 Exception 발생"
throw : 현재 메서드에  프로그래머가 일부러 에러를 발생시킬때  throw new XXXException();
예외 처리방법 1. 예외 복구 : 예외 발생시 다른작업 흐름유도
   : try -catch ~final
2. 예외처리 회피(전파) : 처리하지 않고 호출한 쪽으로 던짐
   : throw ~.. 
3. 예외 전환 : 호출한쪽으로 명확한 의미 전달하기위해 다른예외 전환던짐
    : try -catch( 특정예외 e ){throw 커스텀예외} ~final
from 토비의 스프링 3.1 Vol.1 4장 예외
(최종까지 예외 발생시 예외처리후 해당 쓰레드 종료. )
커스텀한 예외 만드는법.  커스텀예외 참고4가지
1. 항상 이익이 있어야 한다. jdk 있으면 ..있으면있는거 써라
2. 네이밍 규칙 따르기
3. 자바doc을 작성하세요. 
4. 커스텀 예외 던지기전 예외의 이유를 작성하자. 
    원래 발생한 에러가 있으면 같이 전달.  생성자에 Throwable cause 변수 추가. 
(참고. https://m.blog.naver.com/sthwin/221144722072, https://dzone.com/articles/implementing-custom-exceptions-in-java?fromrel=true)
 예외처리 비용.  예외 발생시 발생메서드의 Stack Trace를 모두 메모리에 담고있어야함>> 비용
예외처리로 비즈니스로직 처리 피하는 이유 
로직으로 할수 있는것은 예외던지는것보다 값을 리턴하는게 비용적으로 이득. 
try - catch - finally catch 여러 줄일때 상속관계 인지 주의 할것. 상위 상속관계가 뒤에 
finally 안에 return 을 쓰는 것은 anti 패턴.  finally에 리턴이 있음 try 리턴작동안함. 
e.printStackTrace 로그로 출력하면 안되는 정보들 주의 -개인정보
Multicatch블록 JDK 1.7, 역시 부모자식관계 주의 
try{         }catch(예외1 | 예외2 | 예외3 e) {         }
메서드체이닝 여러 메서드 호출을 연결해 하나의 실행문 표현. 
Init init = new Init();
init.set1(1); init.set2(2); init.set3(3);
메서드 체이닝 :  init.set1(1).set2(2).set3(3);
- setN메서드의 리턴값으로 this를 반환 해서 만듬. 
try-with-resource -알아서 close처리. finally 생략 가능해짐
--컴파일코드 보면 다중 try catch 문이 생기고 catch 블록에서 Throwble로 잡아 close를 해줌. 마지막에도 close()호출. (아래 컴파일 전후 확인)
메이븐 >라이프사이클>컴파일> 타켓 폴더 생성 해당 class파일 확인
@Cleanup -lombok close를 호출해줌.  알고만있고 try-with -resource.로~
   
   
   
   
   
트랜젝션 스프링 기본 트랜젝션 전략에서... 설정을 확인할필요. 
기본적으로 Checekd Exception은 Rollback 하지 않고
unchecked Exception 은 Rollback됨.
스택프레임 스택영역에서 함수 호출 끝난뒤에 돌아갈 정보들을 쌓아놓은곳을 스택프래임이라고한다. 
많이쓰는 기본예외 런타임아닌익셉션 계열 : checked 예외
ClassNotFoundException 
FileNotFoundException 
IOException 
InterruptedException : 특정쓰레드 작업 멈춰달라..
NoSuchMethodException 

RuntimeException계열 : unchecked예외
ArithmeticException : 산술(Arithmetic)연산
ArrayIndexOutOfBoundsException : 배열 인덱스 넘어갈때 
NullPointerException
NumberFormatException
StringIndexOutOfBoundsException
illegalargumentexception 값이 잘못들어옴. 

GoF의 다자인패턴. 

surrond with .. :ctrl alt T

리펙터링 책추천. http://www.yes24.com/Product/Goods/89649360

 

try-with-resource

package study;

import java.io.FileInputStream;
import java.io.InputStream;

public class TryCatchResource {



    public static void main(String[] args) {
        try(InputStream inputStream = new FileInputStream("없는파일.xml")){
            System.out.println(inputStream.toString());
        }catch (Exception e){

        }finally {

        }

    }
}





















package study;

import java.io.FileInputStream;
import java.io.InputStream;

public class TryCatchResource {
    public TryCatchResource() {
    }

    public static void main(String[] args) {
        try {
            try {
                InputStream inputStream = new FileInputStream("없는파일.xml");
                Throwable var2 = null;

                try {
                    System.out.println(inputStream.toString());
                } catch (Throwable var20) {
                    var2 = var20;
                    throw var20;
                } finally {
                    if (inputStream != null) {
                        if (var2 != null) {
                            try {
                                inputStream.close();
                            } catch (Throwable var19) {
                                var2.addSuppressed(var19);
                            }
                        } else {
                            inputStream.close();
                        }
                    }

                }
            } catch (Exception var22) {
            }

        } finally {
            ;
        }
    }
}

 

 

Q1 아래 소스 문제는?

답 : close에 try catch블록이 없다.in 닫을 때 예외 발생하면 out 못닫음 

출처 : 백기선의 스터디할래 강의

Q2 뭣이출력

답: 3

package study;

public class TryCatchFinal {

    public static void main(String[] args) {

       int num = onTryCatchFinally();
        System.out.println(num);
    }

    private static int onTryCatchFinally() {

        try {

            return 1;
        }catch (Exception e){
            return 2;
        }finally {
            return 3;
        }
    }
}

 

package study;

public class TryCatchFinal {

    public static void main(String[] args) {

       int num = onTryCatchFinally(100);
        System.out.println(num);
    }

    private static int onTryCatchFinally(int num) {

        try {
            if (num ==100){
                new RuntimeException();
            }
            return 1;
        }catch (Exception e){
            return 2;
        }finally {
            return 3;
        }
    }
}