[JAVA] 8-10. 예외처리

Jan 02, 2024
[JAVA] 8-10. 예외처리
Contents
try-catch
💡
예외처리요?
자바에서 예외(exception)은 exceptional event를 말한다. 프로그래밍 중, 예외적인 상황에 의해 오류가 발생할 수 있다. 예를들어 인덱스가 배열의 한계를 넘을 수 있는데(나누기 0을 하는 경우 무한대의 값이 나오겠죠?? ), 예외처리는 이런 예외의 오류를 감지하여 처리 또는 종료시키는 것입니다.

try-catch

자바에서는 try-catch 구조를 사용하여 예외를 처리합니다.
만들기
try { // 예외가 발생할 수 있는 코드 } catch (예외클래스 변수) { // 예외를 처리하는 코드 }
단축키 Ctrl + Alt + T :
notion image
이번에 우리가 쓸 건 6. try / catch입니다.
 
자 예제입니다.
class Cal2{ // RuntineException = 엄마가 알려주지 않았을 때 public void divide(int num) throws Exception{ System.out.println(10/num); } } public class TryEx01 { public static void main(String[] args) { Cal2 c2 = new Cal2(); try { c2.divide(5); // 정수값과 0을 넣어보자 } catch (Exception e) { System.out.println("0으로 나눌 수 없어요."); } } }
c2.divide(5);  결과
c2.divide(5); 결과
c2.divide(0); 결과
c2.divide(0); 결과
 

오류 강제 발생 코드

public class TryEx02 { public static void main(String[] args) { // throw키워드 : 오류 강제 발생 throw new RuntimeException("오류 강제 발생"); } }
notion image
 
Exception의 메소드 사용해보기
getMessage() getClass() printStackTrace()
notion image
 
RuntimeException의 메소드 입니다.
RuntimeException의 메소드 입니다.
 
예외처리를 사용하지 않은 프로그램
// 약속 : 1은 정상, 2는 id 제약조건 실패, 3은 pw 제약조건 실패 // 책임 : 데이터베이스 상호작용 class Repository { int insert(String id, String pw) { System.out.println("레포지토리 insert 호출됨"); if (id.length() < 4) { return 2; } if (pw.length() > 10) { return 3; } return 1; } } // 책임 : 유효성 검사 class Controller { String join(String id, String pw) { System.out.println("컨트롤러 회원가입 호출됨"); if (id.length() < 4) { return "유효성검사 : id의 길이가 4자 이상이어야 합니다."; } Repository repo = new Repository(); int code = repo.insert(id, pw); if (code == 2) { return "id가 잘못됐습니다"; } if (code == 3) { return "pw가 잘못됐습니다"; } return "회원가입이 완료되었습니다"; } } public class TryEx03 { public static void main(String[] args) { Controller con = new Controller(); String message = con.join("ssar", "12345678901"); // 여기 System.out.println(message); } }
id와 pw값에 여러가지 값을 넣어 봅시다
pw가 10자리를 넘었을 때
pw가 10자리를 넘었을 때
id가 4자보다 작을 때
id가 4자보다 작을 때
 
정상적인 값을 넣었을 때
정상적인 값을 넣었을 때
 
위의 코드를 예외처리를 사용해보겠습니다
class Repository2 { void insert(String id, String pw) throws Exception{ System.out.println("레포지토리 insert 호출됨"); if (id.length() < 4) { throw new RuntimeException("DB : id길이가 너무 짧습니다. (4자 이상)"); } if (pw.length() > 10) { throw new RuntimeException("DB : pw길이가 너무 길어요. (10자 이하)"); } } } // 책임 : 유효성 검사 class Controller2 { void join(String id, String pw) throws Exception { System.out.println("컨트롤러 회원가입 호출됨"); if (id.length() < 4) { throw new RuntimeException ("Controller : id길이가 너무 짧습니다. (4자 이상)"); } Repository2 repo = new Repository2(); repo.insert(id, pw); } } public class TryEx04 { public static void main(String[] args) { Controller2 con = new Controller2(); try { System.out.println("회원가입 성공"); con.join("ssra", "1234567890"); } catch (Exception e) { System.out.println(e.getMessage()); } } }
일일이 if문을 사용하지 않아도 됩니다. ^O^/
throws 키워드 : 호출 한 클래스에 예외를 위임. 해당 메서드에서 발생할 수 있는 예외를 호출한 곳으로 전파시킬 때 사용된다.
 
 
 
Share article

MiracleCoding