JAVA/JAVA Note

try catch finally / try with resource statements

hoonssss 2023. 8. 16. 13:07
반응형
SMALL
package 생활코딩;

import java.io.*;

public class CheakedExceptionApp {
    public static void main(String[] args) {
        FileWriter f = null;
        try {
            f = new FileWriter("JH");
            f.write("Hello JH");
        } catch (IOException e) {
            e.getMessage();
            e.printStackTrace();
        } finally {
            if (f != null) {
                try{
                    f.close();
                }catch (IOException e){
                    e.getMessage();
                    e.printStackTrace();
                }
            }
        }
    }
}

try catch 로 인하여 close 값이 실행이 안될 수 있으니

Finally 사용

package 생활코딩;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;

import java.io.*;

public class TryWithResource {
    public static void main(String[] args) {
            try(FileWriter f= new FileWriter("JH");){
                f.write("Hello");
            }catch (IOException e){
                e.printStackTrace();
            }
    }
}

f.close 필요없음 자동으로 수행함.

반응형
LIST

'JAVA > JAVA Note' 카테고리의 다른 글

interface, 다형성  (0) 2023.08.16
예외처리  (0) 2023.08.16
indexOf, lastindexOf  (0) 2023.08.16
StringBuilder sb = new StringBuilder();  (0) 2023.08.16
charAt, indexOf  (0) 2023.08.16