본문 바로가기
Programming/Java, Spring

[Java 기초문법] Exceptions 자바 예외 처리

by Renechoi 2022. 10. 20.

[Java 기초문법] by Professional Java Developer Career Starter: Java Foundations @ Udemy

 

 


 

Exceptions 

 

Any time something can go pretty wrong in your program, an exception can be, what we call, thrown, meaning an exception can occur.

 

3 types : 

 

1) checked Exceptions

2) unchecked Exceptions 

3) errors

 

 

Files.lines 와 같이 java.util에서 내재적으로 exception을 일으키도록 구현된 클래스/메소드들도 있다. 

 

 

예외를 처리하는 가장 단순한 방법 

 

 

package com.neutrio.employees;

public class ExceptionTests {
    public static void main(String[] args) {
        String[] array = {"one","two","three"};
        int num = 0;
        try {
            System.out.println(array.length/num);
        } catch (Exception e) {
           e.printStackTrace();
        }
        System.out.println(array[2]);
    }
}

 

There is a hierachy as to Exceptions, and being generic is in a way honored by JVM yet note that specific can be required as the situations goes. 

 

 

 

Returns : 

This is due to the arithmetic exception being thrown
three

 

 

 

Sth wrong / by zero
three

 

 

=> being able to get an idea of what is actually going wrong.

 


 

Unchecked Exceptions 

 

또 다른 방식으로 예외를 처리하는 것은 method signature에 예외 구문을 주는 것

 

 

here, main method will handle whatever happens with his exception now. 

 


 

Finally 

 

public class ExceptionTests {
    public static void main(String[] args) {

        try {
            Files.lines(Path.of("blahblahblah"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("make sure this runs no matter what");
        }
    }
}

 

what happens with the finally block is that any code that we put here is strongly attempted by the JVM to be executed regardless of what went wrong in the try block.

 

 

 

 

반응형