[JAVA] 예외처리 및 입출력

Dawon Ruby Choi·2023년 9월 4일
0

Java

목록 보기
16/18
post-thumbnail

예외처리

예외 : 소스 수정으로 해결 가능한 에러

컴파일 에러 : 빨간줄 (문법에러), 소스를 수정해서 해결
런타임 에러 : 빨간줄이 뜨진 않았으나 실행하면서 나는 에러
시스템 에러 : 메모리 및 하드웨어 문제

예외 클래스 계층 구조

★예외의 최상위 클래스 Exception
Checked Exception 예외처리를 반드시 해줘야함
Unchecked Exception 예외처리 하지않고 코드 수정

구분법 = run tume excpetion 본인 포함 및 후손들 까지 unchecked exception에 해당됨

예외 발생 - try catch문이 있으면 catch로 넘어가고 그게 아니면 중간에 비정상 종료됨!

예외처리 방법

*catch 여러개 작성 가능
강제 발생(thorw)한 곳은 throws 사용하는 편이 좋음

★꼭 수행해야할 것은 finally 안에 넣어주어야함
→try 안에서 수행안하고 넘어가기 때문에

throws

호출해준 메서드한테 위임

계속 호출 메소드로 넘기고 jvm 까지 미처리상태로 넘기면 오류메시지는 안떠도 비정상 종료가 될 수 밖에 없음

throw

예외를 강제로 발생시키는 코드

throws new Exceotion();밑은
실행안하고 넘어갈 코드라서 오류 뜸

예외 강제 발생시킨 메소드에 try catch문을 넣으면 예외가 바로 잡히면서 의미가 없어짐

package com.kh.example.chap01_throws.controller;

public class ThrowsController {
	public void method1() throws Exception{
		System.out.println("method1() 호출됨...");
		method2();
		System.out.println("method1() 종료됨...");

	}
	
	public void method2() throws Exception {
		System.out.println("method2() 호출됨...");
		method3();
		System.out.println("method2() 종료됨...");
	}
	
	public void method3() throws Exception{
		System.out.println("method3() 호출됨...");
		throw new Exception();
		//System.out.println("method3() 종료됨..."); //실행안하고 넘어갈 코드라서 빨간줄
		//throws는 호출해준 메스한테 위임
		//throw는 예외 강제 발생
	}
package com.kh.example.chap01_throws.run;

import com.kh.example.chap01_throws.controller.ThrowsController;

public class Run {

	public static void main(String[] args) {
		System.out.println("프로그램 시작됨...");
		ThrowsController tc = new ThrowsController();
		try {
			tc.method1();
		} catch (Exception e) {
			//e.printStackTrace();
			System.out.println("Exception 예외 catch");
		}
		System.out.println("프로그램 종료됨...");
	}
}
프로그램 시작됨...
method1() 호출됨...
method2() 호출됨...
method3() 호출됨...
프로그램 종료됨...

위 예제 실행 과정

  1. try에서 method1()실행
  2. method2(), mehod3()차례 실행
  3. mehod3()에서 throw new Exception(); 만나고 throws Exception으로 위임
  4. method3을 호출한 method2로 넘어감
  5. 계속 상위 메소드로 넘어가면서 try안에 method1 예외가 발생했으니
  6. catch가 잡아줘서 catch안에 실행
  7. printStackTrace = 어디에서 발생한 예외인지 추척하여 print하겠다.
  8. 마지막 프로그램 종료됨 출력

※참고

사용자 정의 예외

내가 예외클래스 만드는 경우
: Exception 클래스를 상속받아서 예외 클래스 작성

try~with~resource

try 옆에소괄호 열고 io를 받음
따로 finally에서 close처리할 필요 없음

★try ~ with ~ resource로 close 자동처리 하는 법
1) 중복되는 메소드 이름바꿔주기
2) finally 지워주기
3) try 옆 중괄호에 FileWriter fw = new FileWriter("b_char.txt"); 입력
4) 맨 위 FileWriter fw = null; 삭제

입출력 (IO)

인풋 : 읽어 들여오는 것
아웃풋 : 쓰는 것

스트림 : 데이터가 돌아다니는 길 (단방향)
동시 수행을 원하면 2개 스트림 필요

바이트 기반 스트림 - 쪼개서 들여온다, stream붙는다.
문자 기반 - 덩어리로 들어온다, steam이 안붙는다.

★★★

기반스트림 : 실제로 데이터가 오고가는 길 (객체 생성 가능)
보조스트림 : 기반스트림을 보조함 (기반 스트림이 있어야 존재 가능, 혼자 객체 생성x) , 생성자 매개변수에 기반스트림 객체를 감싸고 있음

이클립스를 통한 폴더 및 파일 생성

package com.kh.example.chap00_file.comtroller;

import java.io.File;
import java.io.IOException;

public class FileController {
	public void method() {
		try {
			File f1 = new File("test.txt"); // 자바 내 파일 생성
			f1.createNewFile();
			
			File f2 = new File("C:/test/test.txt"); //c드라이브 내 파일 생성
			f2.createNewFile();
			
			File f3 = new File("C:/temp1/temp2"); //c드라이브 내 폴더 생성
			f3.mkdirs(); // make directorys 
			File f4 = new File("C:/temp1/temp2/test.txt"); //c드라이브 폴더 내 파일 생성
			f4.createNewFile();
			f4.delete();
			
			System.out.println(f2.exists());
			System.out.println(f3.exists());
			System.out.println(f4.exists());
			
			System.out.println(f1.getName());
			System.out.println(f1.getAbsolutePath()); //절대경로(정확한 주소), ex) B강의실에 있음
			System.out.println(f2.getPath()); //상대경로(내기준), ex) 내 눈앞에 있음
			System.out.println(f1.length());
			System.out.println(f4.getParent()); //상위폴더
			
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
}

inputstream : 파일이 없으면 오류문구 출력
outputstream : 파일이 없으면 파일 생성

stream 사용 후 닫아주어야 안전하게 사용 가능
(finally 사용 후 .cloes(); 마지막에 다시 try catch)

예시)

finally { 
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();

finally로 catch문 닫아주는 방법
1) finally 밑에 fw.close(); 로 닫아주기
2) try위에 FileWriter fw = null; 로 범위 영향력 넓히기
3 try밑에 앞에부분 중복되니 제거해주기
4) 밑으로 다시 돌아와서 자동 try catch

덮어씌우기 :
fos = new FileOutputStream("a_byte.txt")

이어쓰기 (출력할 때마다 계속 쌓아져서 출력) :
fos = new FileOutputStream("a_byte.txt", true)

*기본적으로 덮어씌우기인데 이어쓰고 싶으면 옆에 , true만 써주면 됨

보조스트림

: 생성자안에 매개변수로 기반스트림이 들어감

try {
	 FileInputStream fis = new FileInputStream("c_buffer.txt");
			BufferedInputStream bis = new BufferedInputStream(fis);

※exception 상속 관계 고려

 catch (IOException e) {
			e.printStackTrace(); 
		} catch (FileNotFoundException e) {

위 경우는 부모클래스(IOException)가 먼저 나왔기 때문에 오류, 아래로 갈수록 부모 클래스가 되도록 해야함.
(단, 상속관계가 없으면 순서는 상관 없음)

객체 입출력 보조 스트림

mvc(model.view.controller) 패턴

코드 패턴 :각 파일의 역할에 따라 패키지 구분

view :

화면 출력 (브라우저 화면, 자바-콘솔), 사용자에게 보이는 부분

model :

데이터 관련
1) vo : 데이터 저장 임시공간 (임시)
2) dao : 데이터 저장 공간 (영구) 직접 접근

controller :

model과 view를 이어주는 역할과 동시에 결과화면 결정, 데이터 가공(띄어쓰기 지워주는 역할 등)

profile
나의 코딩 다이어리🖥️👾✨

0개의 댓글