일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- FastAPI
- 객체지향
- JDBC
- 이클립스
- 생활코딩
- crud
- Java
- 자바
- 컬렉션프레임워크
- spring
- 자바문제
- 맥
- ibatis
- ddit
- Homebrew
- 대덕인재개발원
- 반복문
- Android
- nodejs
- Error
- html
- Oracle
- 배열
- python
- Mac
- servlet
- API
- 단축키
- jsp
- pyqt
Archives
- Today
- Total
romworld
예외처리 본문
package f_exception;
import java.util.concurrent.TimeUnit;
import e_oop.ScanUtil;
public class ExceptionHandling {
/*
* 에러
* - 컴파일 에러 : 컴파일 시에 발생되는 에러(빨간줄)
* - 논리적 에러 : 실행은 되지만, 의도와 다르게 동작하는 에러(버그)
* - 런타임 에러 : 실행시에 발생되는 에러
*
* 런타임 에러
* - 런타임 에러 발생 시 발생한 위치에서 프로그램이 비정상적으로 종료된다.
* - 에러 : 프로그램코드에 의해 수습될 수 없는 심각한 오류(처리 불가)
* - 예외 : 프로그램코드에 의해서 수습될 수 있는 다소 미약한 오류 (처리 가능)
*
* 예외
* - 모든 예외는 Exception 클래스의 자식 클래스이다.
* - RuntimeException 클래스와 그 자식들은 예외처리가 강제되지 않는다.
* - (RuntimeException 클래스와 그 자식들을 제외한) Exception 클래스의 자식들은
* 예외처리가 강제된다.
*
* 예외처리(try-catch)
* - 예외처리를 통해 프로그램이 비정상적으로 종료되는 것을 방지할 수 있다.
* - try {} catch(Exception e){}
* - try 블럭 안의 내용을 실행 중 예외가 발생하면 catch로 넘어간다.
* - catch () 안에는 처리할 예외를 지정해줄 수 있다.
* - 여러종류의 예외를 처리할 수 있도록 catch는 하나 이상 올 수 있다.
* - 발생한 예외와 일치하는 catch블럭 안의 내용이 수행된 후 try-catch를 빠져나간다.
* - 발생한 예외와 일치하는 catch가 없을 경우 예외는 처리되지 않는다.
* */
public static void main(String[] args) {
int input=ScanUtil.nextInt();//만약 문자를 입력하게되면 (런타임 에러) 발생
// try {
// TimeUnit.SECONDS.sleep(1);
//// } catch(Exception e) { //이거 하나만 있어도 에러처리 다 가능함!!!!
//// e.printStackTrace();
//// }
// } catch (NumberFormatException e) { // Exception이 맨 위에있으면 아래 코드가 필요없다 왜냐하면 Exception이
//모든 오류를 다 처리하기에 맨 밑에있어야됨
// System.out.println("NumberFormatException");
// } catch (InterruptedException e) {
// e.printStackTrace();
// System.err.println("타임유닛 에러!");
// } catch (Exception e) {// 이렇게 Exception이 맨 밑에 있어야됨
// e.printStackTrace();
// }
try {
int result = 10 / 0;
System.out.println(result);
}catch(ArrayIndexOutOfBoundsException | ArithmeticException e) {
e.printStackTrace(); //에러 메세지를 출력한다.
System.out.println("숫자를 0으로 나눌 수 없습니다.");
// }catch(ArrayIndexOutOfBoundsException e) { //alt + ctrl + spacebar 누르면 자동완성
// e.printStackTrace(); //에러 메세지를 출력한다.
}catch(NullPointerException e) {
// 아무 조치도 하지 않지만 프로그램이 종료되지 않는다.
}catch(Exception e) {
//예상치 못한 모든 에러 처리
e.printStackTrace();
}
System.out.println("프로그램 정상 종료!");
//try catch로 묶으면 개발자가 원할 때 종료시킬 수 있다.
}
}
package f_exception;
import java.io.IOException;
public class TrowException {
/*
* 예외 발생시키기 - throw new Exception();
* throw 예약어와 예외 클래스 객체로 예외를 고의적으로 발생시킬 수 있다.
*/
public static void main(String[] args) {
IOException ioe = new IOException();
try {
throw ioe;
} catch (IOException e) {
e.printStackTrace();
}
UserException ue = new UserException();
try {
if (1 == 1) {
throw ue; // 이 프로그램에게 예외사항을 던져주겠다!
}
} catch (UserException e) {
e.printStackTrace();
}
}
}
package f_exception;
import java.util.concurrent.TimeUnit;
public class ThrowsException {
/*
* 메서드에 예외 선언하기 - 메서드 호출 시 발생할 수 있는 예외를 선언해줄 수 있다. - 반환타입 method() throws
* Exception {} - 메서드의 구현부 끝에 throws 예약어와 예외 클래스명으로 예외를 선언할 수 있다. - 예외를 선언하면
* 예외처리를 하지 않고 자식을 호출한 메서드로 예외처리를 미룬다.
*/
public static void main(String[] args) {
new ThrowsException().methodA();
new ThrowsException().methodB();
System.out.println("check");
}
private void methodB() {
try {
test();
} catch (InterruptedException e) {
System.out.println("methodA 에러처리!");
}
}
private void methodA() {
try {
test();
} catch (InterruptedException e) {
System.out.println("methodB 에러처리!");
}
}
private void test() throws InterruptedException {
TimeUnit.SECONDS.sleep(1);
InterruptedException ie = new InterruptedException();
throw ie;
}
// exception을 미루는 이유는 여기말고 쓰고있는 곳이 여러군데일 수 있기때문에 예외처리를 미룬다
}
package f_exception;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Finally {
/*
* finally
* - 필요에 따라 try-catch 뒤에 finally를 추가할 수 있다.
* - finally는 예외 발생여부와 상관없이 가장 마지막에 수행된다.
*
* 자동 자원 반환 (JDK 1.7)
* - try(변수 선언; 변수 선언) {} catch(Exception e){}
* - 사용 후 반환이 필요한 객체를 try의 ()안에 선언하면
* try블럭 종료 시 자동 반환
* */
public static void main(String[] args) {
FileInputStream fis = null; // 파일 읽기 준비(내가 사용하고 있는 프로그램이 특정 파일을 읽어오겠당)
try {
fis = new FileInputStream("d:\\file.txt");
}catch(FileNotFoundException e) {
System.out.println("파일 없음");
}finally {
System.out.println("finally");
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 예외 발생 : try -> catch -> finally
// 예외 없음 : try -> finally ~~ ^^
try(FileOutputStream fos = new FileOutputStream("d:\\file.txt")){
String str = "아무내용이나 써보자!";
byte[] byts = str.getBytes();
for(int i = 0; i< byts.length; i++) {
fos.write(byts[i]);
}
}catch(FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) { //input output exception
e.printStackTrace();
}
// fos. try문이 종료된 이후에는 fos는 사라짐 try-catch블럭 안에서만 사용가능~!~@@@
}
}
'JAVA > 개념정리' 카테고리의 다른 글
컬렉션 프레임워크 (0) | 2022.10.10 |
---|---|
API 클래스 (0) | 2022.10.10 |
추상 클래스와 인터페이스 (0) | 2022.10.09 |
Chapter 07 상속 (0) | 2022.10.04 |
Chapter 06 객체지향 프로그래밍 (2) (0) | 2022.09.30 |
Comments