์ƒ์„ธ ์ปจํ…์ธ 

๋ณธ๋ฌธ ์ œ๋ชฉ

[Java] Exception, try-catch-finally, try-with-resources

๐Ÿ˜Ž ์ง€์‹ in Action/Java & Kotlin

by :ํ•ดํ”ผ๋ž˜๋น—๐Ÿพ 2023. 12. 24. 12:00

๋ณธ๋ฌธ

Exception?

ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ์ค‘์— ๋ฐœ์ƒํ•˜์—ฌ ํ”„๋กœ๊ทธ๋žจ ๋ช…๋ น์˜ ์ •์ƒ์ ์ธ ํ๋ฆ„์„ ๋ฐฉํ•ดํ•˜๋Š” ์ด๋ฒคํŠธ

 
- ๋ฉ”์†Œ๋“œ ๋‚ด์—์„œ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ๋ฉ”์†Œ๋“œ๋Š” ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ณ  ์ด๋ฅผ ๋Ÿฐํƒ€์ž„ ์‹œ์Šคํ…œ์— ์ „๋‹ฌํ•œ๋‹ค
===> ์˜ˆ์™ธ ๊ฐœ์ฒด์—๋Š” ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•œ ๋‹น์‹œ์˜ ํ”„๋กœ๊ทธ๋žจ ์ƒํƒœ, ์œ ํ˜•์„ ํฌํ•จํ•œ ์˜ค๋ฅ˜์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ๋‹ด๊ณ  ์žˆ๋‹ค

exception handler๋ฅผ ์ฐพ์ง€ ๋ชปํ•œ ์ฑ„ ํ˜ธ์ถœ ์Šคํƒ์˜ ๋ชจ๋“  ๋ฉ”์„œ๋“œ๋ฅผ ๊ฒ€์ƒ‰ํ•œ ๊ฒฝ์šฐ ๋Ÿฐํƒ€์ž„ ์‹œ์Šคํ…œ์ด ์ข…๋ฃŒ๋œ๋‹ค.

 
try : exception์— ๋Œ€ํ•œ handler(catch)๋ฅผ ์ œ๊ณตํ•ด์•ผ ํ•œ๋‹ค
throws : exception์„ ๋˜์งˆ ์ˆ˜ ์žˆ๋Š” ๋ฉ”์„œ๋“œ๋ผ๋Š” ๊ฒƒ์„ ๋ช…์‹œํ•˜๋Š” ๊ตฌ๋ฌธ

๋˜์งˆ ์ˆ˜ ์žˆ๋Š” ํด๋ž˜์Šค์™€ ์„œ๋ธŒ ํด๋ž˜์Šค

Throwable ํด๋ž˜์Šค

 

์˜ˆ์™ธ์˜ ์žฅ์ 

1. ์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ ์ฝ”๋“œ๋ฅผ ์ผ๋ฐ˜ ์ฝ”๋“œ์™€ ๋ถ„๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค
2. ํ˜ธ์ถœ ์Šคํƒ ์œ„๋กœ ์˜ค๋ฅ˜๋ฅผ ์ „ํŒŒํ•  ์ˆ˜ ์žˆ๋‹ค
3. ์˜ค๋ฅ˜ ์œ ํ˜•์„ ๊ทธ๋ฃนํ™”ํ•˜๊ณ  ๊ตฌ๋ณ„ํ•  ์ˆ˜ ์žˆ๋‹ค


 

3๊ฐ€์ง€ ์ข…๋ฅ˜์˜ ์˜ˆ์™ธ

1. Checked Exception

์ž˜ ์ž‘์„ฑ๋œ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ์˜ˆ์ƒํ•˜๊ณ  ๋ณต๊ตฌํ•ด์•ผ ํ•˜๋Š” ์˜ˆ์™ธ
Error, RuntimeException๊ณผ ๊ทธ ์„œ๋ธŒ ํด๋ž˜์Šค๋ฅผ ์ œ์™ธํ•œ ๋ชจ๋“  Exception
ex) java.io.FileNotFoundException

2. Error

์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์™ธ๋ถ€์— ์žˆ๋Š” ์˜ˆ์™ธ์ ์ธ ์กฐ๊ฑด, ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ์˜ˆ์ƒํ•˜๊ฑฐ๋‚˜ ๋ณต๊ตฌํ•  ์ˆ˜ ์—†๋Š” ์˜ˆ์™ธ
์˜ค๋ฅ˜๋Š” Catch ๋˜๋Š” Specific Requirement(ํš๋“ ๋˜๋Š” ์ง€์ • ์š”๊ตฌ์‚ฌํ•ญ)์˜ ์ ์šฉ์„ ๋ฐ›์ง€ ์•Š์Œ
Error์™€ ๊ทธ ํ•˜์œ„ ํด๋ž˜์Šค
ex) java.io.IOError

3. Runtime Exception

์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๋‚ด๋ถ€์— ์žˆ๋Š” ์˜ˆ์™ธ์ ์ธ ์กฐ๊ฑด, ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ์˜ˆ์ƒํ•˜๊ฑฐ๋‚˜ ๋ณต๊ตฌํ•  ์ˆ˜ ์—†์Œ
๋…ผ๋ฆฌ ์˜ค๋ฅ˜๋‚˜ API์˜ ๋ถ€์ ์ ˆํ•œ ์‚ฌ์šฉ๊ณผ ๊ฐ™์€ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ๋ฒ„๊ทธ
์˜ˆ์™ธ ๋ฐœ์ƒ์„ ์•ผ๊ธฐํ•œ ๋ฒ„๊ทธ๋ฅผ ์ œ๊ฑฐํ•ด์•ผ ํ•จ
ex) NullPointerException


 

try-catch-finally์™€ try-with-resources (Java SE7)

try-with-resources ๋ฌธ์€ Closeable๊ณผ ๊ฐ™์€ ๋ฆฌ์†Œ์Šค(ex Stream)๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ƒํ™ฉ์— ์ ํ•ฉํ•จ
// Note: This class will not compile yet.
import java.io.*;
import java.util.List;
import java.util.ArrayList;

public class ListOfNumbers {

    private List<Integer> list;
    private static final int SIZE = 10;

    public ListOfNumbers () {
        list = new ArrayList<Integer>(SIZE);
        for (int i = 0; i < SIZE; i++) {
            list.add(new Integer(i));
        }
    }

    public void writeList() {
	// The FileWriter constructor throws IOException, which must be caught.
        PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));

        for (int i = 0; i < SIZE; i++) {
            // The get(int) method throws IndexOutOfBoundsException, which must be caught.
            out.println("Value at: " + i + " = " + list.get(i));
        }
        out.close();
    }
}

IOException ๊ณผ IndexOutOfBoundsException์ด ์ฒ˜๋ฆฌ๋˜์–ด์•ผ ํ•œ๋‹ค
 

ex) ์œ„์˜ ์ฝ”๋“œ๋ฅผ Exception ์ฒ˜๋ฆฌ ํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์•Œ์•„๋ณด์ž

1. ์˜ˆ์™ธ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ฌ ์ˆ˜ ์žˆ๋Š” (1)๊ฐ ์ฝ”๋“œ ์ค„์„ try ๋ธ”๋ก ๋‚ด์— ๋ฐฐ์น˜ํ•˜๊ณ  (2) ๊ฐ๊ฐ์— ๋Œ€ํ•ด ๋ณ„๋„์˜ exception handler๋ฅผ ์ œ๊ณตํ•œ๋‹ค

private List<Integer> list;
private static final int SIZE = 10;

public void writeList() {
    PrintWriter out = null;
    try { //ํ•˜๋‚˜์˜ try block
        System.out.println("Entered try statement");
        FileWriter f = new FileWriter("OutFile.txt"); // IOException
        out = new PrintWriter(f);
        for (int i = 0; i < SIZE; i++) {
            out.println("Value at: " + i + " = " + list.get(i)); // IndexOutOfBoundsException
        }
    }
    catch and finally blocks  . . .
}

 

try {

} catch (IndexOutOfBoundsException e) {
    System.err.println("IndexOutOfBoundsException: " + e.getMessage());
} catch (IOException e) {
    System.err.println("Caught IOException: " + e.getMessage());
}

 

Java SE 7 ์ด์ƒ์—์„œ๋Š” ๋‹จ์ผ catch ๋ธ”๋ก์ด ๋‘ ๊ฐ€์ง€ ์ด์ƒ์˜ ์˜ˆ์™ธ ์œ ํ˜•์„ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์Œ
catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

 

finally ๋ธ”๋ก

์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•ด๋„ ๋ธ”๋ก์ด ์‹คํ–‰๋œ๋‹ค. ๊ทธ๋ž˜์„œ ์‹ค์ˆ˜๋กœ return, continue ์— ์˜ํ•ด ์ •๋ฆฌ ์ฝ”๋“œ๋ฅผ ์šฐํšŒํ•˜๋Š” ๊ฒƒ์„ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ๋‹ค.
์œ„์˜ ์˜ˆ์ œ์—์„œ 3๊ฐ€์ง€ ๋ฐฉ๋ฒ• ์ค‘ ํ•˜๋‚˜๋กœ finally ๋ธ”๋ก์ด ์ข…๋ฃŒ๋  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋‹ค์†Œ ๋ณต์žกํ•˜๋‹ค.

  1. FileWriter ๊ตฌ๋ฌธ์ด ์‹คํŒจํ•˜๊ณ  IOException์ด ๋ฐœ์ƒํ•œ๋‹ค
  2. list.get(i) ๊ตฌ๋ฌธ์ด ์‹คํŒจํ•˜๊ณ  IndexOutOfBoundsException ์ด ๋ฐœ์ƒํ•œ๋‹ค
  3. ๋ชจ๋“  ๊ฒƒ์ด ์„ฑ๊ณต๋˜๊ณ , try block์ด ์ •์ƒ์ ์œผ๋กœ ์ข…๋ฃŒ๋œ๋‹ค

์ด๋ ‡๊ฒŒ 3๊ฐ€์ง€ ๋ฐฉ๋ฒ• ์ค‘ ํ•˜๋‚˜๋กœ ์‹คํ–‰๋  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ฝ”๋“œ๊ฐ€ ์ž‘์„ฑ๋˜์–ด์•ผ ํ•œ๋‹ค

finally {
    if (out != null) { 
        System.out.println("Closing PrintWriter");
        out.close(); 
    } else { 
        System.out.println("PrintWriter not open");
    } 
    if (f != null) {
	    System.out.println("Closing FileWriter");
	    f.close();
	}	
}

 

try - with - resources ๊ตฌ๋ฌธ์„ finally block ๋Œ€์‹ ์— ์‚ฌ์šฉํ•ด๋ผ

try-with-resources ๊ตฌ๋ฌธ์€ ๋” ์ด์ƒ ํ•„์š”ํ•˜์ง€ ์•Š์€ ์‹œ์Šคํ…œ ๋ฆฌ์†Œ์Šค๋ฅผ ์ž๋™์œผ๋กœ releaseํ•œ๋‹ค

public void writeList() throws IOException {
    try (FileWriter f = new FileWriter("OutFile.txt");
         PrintWriter out = new PrintWriter(f)) {
        for (int i = 0; i < SIZE; i++) {
            out.println("Value at: " + i + " = " + list.get(i));
        }
    }
}

try-with-resources ?

 ๊ตฌ๋ฌธ์˜ ๋์—์„œ resource๊ฐ€ ๋‹ซํžˆ๋Š” ๊ฒƒ์ด ๋ณด์žฅ๋œ๋‹ค
java.lang.AutoCloseable์ด๋‚˜ java.io.Closeable์„ ๊ตฌํ˜„ํ•˜๋Š” Object๋Š” resource๋กœ ์‚ฌ์šฉ๋  ์ˆ˜ ์žˆ๋‹ค
 
Java SE 7์ดํ›„์—๋Š” FileReader, BufferedReader ๊ฐ€ java.lang.AutoCloseable์„ ๊ตฌํ˜„ํ•œ๋‹ค. 
๊ทธ๋Ÿฌ๋ฏ€๋กœ, try-with-resources์— ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ณ , try๋ฌธ์ด ์ •์ƒ์ ์œผ๋กœ ์™„๋ฃŒ๋˜์—ˆ๋Š”์ง€ ์—ฌ๋ถ€์— ๊ด€๊ณ„์—†์ด resources๋Š” ๋‹ซํžˆ๊ฒŒ ๋œ๋‹ค.

static String readFirstLineFromFile(String path) throws IOException {
	    try (FileReader fr = new FileReader(path);
	         BufferedReader br = new BufferedReader(fr)) {
	        return br.readLine();
	    }
	}

Java SE 7 ์ด์ „์—๋Š” finally ๋ธ”๋ก์—์„œ ๋ฆฌ์†Œ์Šค๋ฅผ ๋‹ซ๋„๋ก ์ฒ˜๋ฆฌํ–ˆ๋‹ค. ํ•˜์ง€๋งŒ, ๋ฆฌ์†Œ์Šค ๋ˆ„์ˆ˜๊ฐ€ ์žˆ์„ ์ˆ˜ ์žˆ๋‹ค. ๋ฆฌ์†Œ์Šค์˜ close ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•ด์„œ ์šด์˜์ฒด์ œ์—๊ฒŒ ํ•ด์ œ๋ฅผ ์š”์ฒญํ•ด์•ผ ํ•œ๋‹ค. ํ•˜์ง€๋งŒ, GC๊ฐ€ ๋ฆฌ์†Œ์Šค๋ฅผ ํšŒ์ˆ˜ํ•˜๊ธฐ ์ „์— ์ด ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•˜์ง€ ๋ชปํ•˜๋ฉด ๋ฆฌ์†Œ์Šค๋ฅผ ํ•ด์ œํ•˜๋Š” ๋ฐ ํ•„์š”ํ•œ ์ •๋ณด๊ฐ€ ์†์‹ค๋œ๋‹ค.
 
- ๋ฆฌ์†Œ์Šค์˜ ๋ฉ”์„œ๋“œ๋Š” ์ƒ์„ฑ ์ˆœ์„œ์™€ ๋ฐ˜๋Œ€ ์ˆœ์„œ๋กœ ํ˜ธ์ถœ๋œ๋‹ค.

public static void writeToFileZipFileContents(String zipFileName,
                                           String outputFileName)
                                           throws java.io.IOException {

    java.nio.charset.Charset charset =
         java.nio.charset.StandardCharsets.US_ASCII;
    java.nio.file.Path outputFilePath =
         java.nio.file.Paths.get(outputFileName);

    // Open zip file and create output file with 
    // try-with-resources statement

    try (
        java.util.zip.ZipFile zf =
             new java.util.zip.ZipFile(zipFileName);
        java.io.BufferedWriter writer = 
            java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
    ) {
        // Enumerate each entry
        for (java.util.Enumeration entries =
                                zf.entries(); entries.hasMoreElements();) {
            // Get the entry name and write it to the output file
            String newLine = System.getProperty("line.separator");
            String zipEntryName =
                 ((java.util.zip.ZipEntry)entries.nextElement()).getName() +
                 newLine;
            writer.write(zipEntryName, 0, zipEntryName.length());
        }
    }
}

 

 
 


https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html

 

Lesson: Exceptions (The Java™ Tutorials > Essential Java Classes)

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated

docs.oracle.com

 

728x90

๊ด€๋ จ๊ธ€ ๋”๋ณด๊ธฐ