<try catch finally>
package exception;
public class MainExceptionHanding {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5 };
int x = 10;
for (int i = 0; i <= arr.length; i++) {
try {
System.out.println(arr[i]);
x = x/0;
} catch (ArrayIndexOutOfBoundsException e) {
//System.out.println(e.toString());
//System.out.println(e.getMessage());
//e.printStackTrace();
} catch(ArithmeticException ae) {
//ae.printStackTrace();
//System.out.println(ae.getMessage());
} catch(Exception otherException) {
System.out.println(otherException);
}
} // for
}
}
e.getMessage()
에러원인 간단하게 출력
e.toString()
무슨 오류인지 모두 출력
e.printStackTrace() - sysout 없이 그대로 쓰임
에러의 발생근원지를 찾아서 단계별로 에러 출력
개발을 할 때는 이런 Trace를 써도 되지만 운영을 할 때는 이러한 정보는 보안성이 있기 때문에 log 프레임워크를 쓴다
catch를 여러개 쓸 수 있는데 위에서부터 순서대로 내려오기 때문에 Exception 객체를 맨 위에 쓰게 되면 모든 오류가 여기 들어가기 때문에 맨 아래에 내려줘야한다.
<Throws>
method에서 처리해야 할 하나 이상의 예외를 호출한 곳으로 전달(예외가 없어지는게 아닌 단순히 전달)
class ThrowsTest{
public static void main(string[] args{
try{
new ThrowsTest().method1();
} catch(ArithmeticException e){
System.out.println(e);
}
}
public voidmethod1() throws ArithmeticException{
method2();
}
}
<사용자 정의 Exception>
1) 사용자 정의 Exception class 정의 - Exception 상속
class UserException extends Exception{
public UserException(){
super("user exception message");
}
}
2) 사용자 정의 Exception 발생 - thorw new 사용자 정의 Exception();
public void method() throws UserException{
throw new UserException
}
3) 처리 - throws 사용자정의 Exception 호출 시 try~catch~finally
public void useMethod(){
try{
method();
}catch(UserException e){
System.out.println(e);
}
}
package exception;
public class UserExceptionTest {
public static void main(String[] args) {
//3. Exception 발생되는 메소드 호출 시 처리
//new UserExceptionTest().exception();을 쓰면서 오류가 여기에 넘어오게 되었으니까 얘를 처리할 try~catch가 필요함
try {
new UserExceptionTest().exception();
} catch (UserException e) {
e.printStackTrace();
}
}
//2. 사용자 정의 예외 클래스 발생 - throw new 사용자정의예외클래스();
public void exception() throws UserException {
//throw + 예외클래스(클래스니까 new해서 만들어준 것임)
//RuntimeException을 상속받은게 아니라 Exception을 상속받았기 때문에 throws UserException을 해줘야함
throw new UserException("사용자 예외 발생했습니다");
}
}
//1. 사용자 정의 예외 클래스 : Exception상속
class UserException extends Exception{
public UserException() {
super("User Exception");
}
public UserException(String message) {
super(message);
}
}
<try-with-resources>
더보기
try-catch-finally로 하면 엄청 지저분함
public static void main(String args[]) throws IOException {
FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream("file.txt");
bis = new BufferedInputStream(is);
int data = -1;
while((data = bis.read()) != -1){
System.out.print((char) data);
}
} finally {
// close resources
if (is != null) is.close();
if (bis != null) bis.close();
}
}
public static void main(String args[]) {
try (
FileInputStream is = new FileInputStream("file.txt");
BufferedInputStream bis = new BufferedInputStream(is)
) {
int data = -1;
while ((data = bis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
코드를 보면, try(...) 안에 InputStream 객체 선언 및 할당했다.
여기에서 선언한 변수들은 try 안에서 사용할 수 있는데 코드의 실행 위치가 try 문을 벗어나면 try-with-resources try(...) 안에서 선언된 객체의 close() 메소드들을 호출한다.
따라서 finally에서 close()를 명시적으로 호출해줄 필요가 없다!
'Backend > Java' 카테고리의 다른 글
Java 코딩테스트를 위한 문법 (0) | 2022.08.02 |
---|---|
Java 직렬화 (0) | 2022.07.27 |
Java Generic, Collection에 대해 (0) | 2022.07.26 |
Java Override & Overload (0) | 2022.07.20 |
Java Grammer (version. Jiwon) (0) | 2022.07.19 |