Sesac 10일차

SungMin·2022년 10월 18일
0

Sesac-Java/Spring

목록 보기
6/13

예외처리

예외

  • 사용자의 잘못된 조작 또는 개발자의 잘못된 코딩으로 인한 오류
  • 예외가 발생되면 프로그램 종료
  • 예외 처리 추가하면 정상 실행 상태로 돌아갈 수 있음

예외의 종류

  • 컴파일 오류 (Compile Error) – 컴파일 불가
  • 런타임 오류 (Runtime Error) – 실행 중 오류
  • 논리 오류 (Logical Error) – 버그 (흐름상 잘못된 코딩)
public class ErrorExam {

	public static void main(String[] args) {
		// 예외의 종류
		int a = 1.2; // compile error
		
		// runtime exception
		System.out.println(4 / 0); // Arithmetic
		System.out.println(new String().charAt(1)); // IndexOutOfBounds
		String str = null;
		System.out.println(str.equals("")); // NullPointer
		int[] arrs = new int[-1]; // NegativeArraySize
		String s = "Exception";
		int count = s.indexOf("a");
		int[] arrays = new int[count]; // NegativeArraySize
		System.out.println(arrays);
		
		// exception
		new File("").createNewFile();

	}

}

예외처리 방법

if문을 이용한 예외처리

  • 간단한 처리에 좋음
  • 코드만 봐서는 if문 흐름인지, 예외처리인지 구분이 힘든 게 단점
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ErrorExam01_If {

	public static void main(String[] args) {
		// if문을 이용한 예외처리
		String numStr = " 123";
		Pattern p = Pattern.compile("^[0-9]*$");
		Matcher m = p.matcher(numStr);
		boolean isNumber = m.matches();
		if(isNumber) {
			// 사전 작업없이 그냥 실행시키면 에러 발생
			// if문을 사용해서 해당 작업이 가능할 때 만 실행 되도록 작성.
			int num = Integer.parseInt(numStr);
		}
		System.out.println("isNumber : "+isNumber);
		
		Object obj = new String("a");
		if(obj instanceof Integer) {
			int a = (Integer) obj;
			System.out.println("a1 : "+a);
		} else if(obj instanceof String) {
			String a = (String) obj;
			System.out.println("a2 : "+a);
		}

	}

}

try-catch-finally

  • 예외 발생시 프로그램 종료 막고, 정상 실행 유지할 수 있도록 처리
    -Exception (일반 예외) : 반드시 작성해야 컴파일 가능
    -Runtime Exception (실행 예외) : 개발자 경험 의해 작성 (컴파일시 체크 X)
  • 다양한 예외처리 종류를 할 수 있는 만큼 문제를 정확히 알 수 있게 됨
  • try – catch – finally 블록 이용해 예외 처리 코드 작성
public class ErrorExam02_try {

	public static void main(String[] args) {
		// try-catch-finally
		// 정상실행 되었을 때 흐름
		String numStr = "123";
		try {
			int num = Integer.parseInt(numStr); // 숫자를 문자열로 변경
			System.out.println(num);
		} catch (NumberFormatException e) { // 포괄적으로 모든 number를 받아줌
			e.printStackTrace(); // 예외문을 그대로 출력해줌
		} finally {
			System.out.println("항상 실행1");
		}
		
		//예외가 발생했을 경우의 흐름
		Object obj = new String("a");
		try { // 형변환 작업
			int a = (Integer) obj;
			System.out.println("정상실행 여부 확인 : "+a);
		} catch (ClassCastException e) { // 형변환에 실패했을 경우
			System.out.println(e.getMessage()); // 내용을 메세지로 수신
		} finally {
			System.out.println("항상 실행2");
		}

	}

}

파일의 내용을 읽어오는 코드 예외처리

//연습문제01
// 파일의 내용을 읽어오는 코드 예외처리
// try-catch-finally이용
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ErrorExam_sonagi {

	public static void main(String[] args) throws IOException {
		
		BufferedReader reader = null; // reader를 메인메소드에서 선언해줌
			try {
				reader = new BufferedReader(new FileReader("data/소나기.txt"));
				String text = "";
				while(true) {
				String data = reader.readLine();
				if(data == null) 
					break;
				text += data + "\n";
				}
				System.out.println(text);
			} catch (FileNotFoundException e) {
				System.out.println("파일이 존재하지 않을 때");
				e.printStackTrace();
			} catch (IOException e) {
				System.out.println("입출력 관련 에러");
				e.printStackTrace();
			} finally {
				try {
					reader.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
	}

}

예외 떠넘기기

  • 메소드를 호출한 곳으로 떠넘기는 역할
import java.rmi.AccessException;

public class ThrowsExam {

	private String strNum;
	private String num;
	
	public String getStrNum() {
		return strNum;
	}
	
	public void setStrNum(String strNum) {
		this.strNum = strNum;
	}
	
	public String getNum() {
		return num;
	}
	
	public void setNum(String num) {
		this.num = num;
	}
	
	public void check() throws AccessException{
		try {
			int num = Integer.parseInt(this.strNum);
			Object obj = new String(this.num);
			int a = (Integer) obj;
		} catch (NumberFormatException e) {
			throw new AccessException("숫자변환 실패");
		} catch (ClassCastException e) {
			throw new AccessException("형변환 실패");
		}
	

	}

}

Maven

  • 자바 프로젝트 관리 도구 (Build Tool)
  • 컴파일 / 빌드 / 수행 / 테스트 / 배포 + 라이브러리 의존성 관리
  • Apache의 중앙 저장소 또는 별도의 자체 중앙 저장소 구축 가능

Spring MVC

Spring Web MVC

  • Model – View – Controller 의 약자
  • Presentation 과 Business 를 분리시키기 위해 사용
  • MVC 아키텍처의 일반적인 흐름

DB에서 수행하는 작업 - CRUD

  • 삽입 - create
  • 조회 - read
  • 수정 - update
  • 삭제 - delete

Controller 에서 주로 사용되는 Annotation

종류사용 위치사용 예
@Controller클래스@Controller /public class HomeController { }
@RestController클래스@RestController /public class HomeController { }
@RequestMapping메소드@RequestMapping("/home") /public String home() { }
@GetMapping / @PostMapping메소드@GetMapping("/home") /public String home() { }
@RequestParam메소드 매개변수@GetMapping("/home") /public String home( /@RequestParam String id) { }
@ModelAttribute메소드 매개변수@GetMapping("/home") /public String home( /@ModelAttribute DataVO dataVO) { }
@PathVariable메소드 매개변수@GetMapping("/home/{address}") /public String home( /@PathVariable String address) { }
@ResponseBody메소드@GetMapping("/home") /@ResponseBody /public String home() { /return "값"; }
profile
초보 개발자의 학습 저장용 블로그

0개의 댓글