[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.
'Programming > Java, Spring' 카테고리의 다른 글
[Java 기초문법] 문자열 비교하기 , 필드, 메소드, 변수의 scope와 static, 열거형 (enum) (0) | 2022.10.21 |
---|---|
[Java 기초문법] Generic usage case (0) | 2022.10.21 |
[Java 기초문법] Streams API | Streams, stream의 다양한 메소드, sum, sort, filter (0) | 2022.10.20 |
[Java 기초문법] collections, list, linked list, looping with iterators (0) | 2022.10.20 |
[Java 기초문법] 자바 람다 Lambdas, delegate method (0) | 2022.10.20 |