본문 바로가기
JAVA

예외처리: try-catch-finally, throws, throw

by EUN-JI 2023. 7. 15.

★ 예 외 처 리 ★

[ try - catch - finally ]

try

: 예외 발생을 조사할 문장;

 

catch(예외 클래스 변수명)

: 예외가 발생했을 때 실행할 코드;

 

finally

: 마지막에 반드시 실행해야 하는 코드;

 

[ throws ]

: 예외를 떠넘김 

 

[ throw ] 

: 예외를 강제로 발생시킴

import java.net.MalformedURLException;
import java.net.URL;
import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		//1.Error(오류) : 실행자체가 불가
		//2.Exception(예외) : (실행은 되나) (Run Time)실행 중에 문제가 발생!
		
		//in a; //에러... 문법적으로 문제 발생.  - 실행도 안됨
		
		//예외: Exception)문법적으로는 에러가 아닌데..실행할 수 없는 경우..
		System.out.println("예외처리에 대해 알아봅시다.");
		
		//예외의 대표 경우..
		
		//1) 0 나눗셈.
		int a=0;
//		System.out.println(10/a);
		
		//예외가 발생하면 그 위치 다음 줄부터는 실행이 안됨.
		//앱에서는 예외가 발생하면 앱이 다운됨. 사용자가 엄청 싫어함!!
		//개발자는 설사 예외가 발생해도 앱이 다운되지 않도록
		//처리할 필요가 있음.
		//이를 [예외처리]라고 부름
		
		//예외가 발생할 가능성이 있는 코드를 감싸는 try{}문을 사용함
		try {
			System.out.println(10/a);
		}catch(ArithmeticException e) {
			System.out.println("예외가 발생했다.!!");
		}
		System.out.println("---------------------------");
		//2) 배열의 인덱스번호를 잘못 작성
		int [] aaa= new int [3];
		try {
			for(int i=0; i<4; i++) {
				System.out.println(aaa[i]);
		}
		}catch(ArrayIndexOutOfBoundsException e) {
			System.out.println("인데스번호 틀렸어" + e.getMessage());
		}
		
		//3)null참조변수로 객체의 기능메소드를 사용문제
		String s = null;
		try {
		System.out.println(s.length());
		}catch(NullPointerException e) {
			System.out.println(e.getMessage());
		}
		
		//이 외에도 많은 종류의 예외가 존재함. 앞으로 종종 보게될 것임.
		
		//경우에 따라서는 2개의 이상의 예외가 발생할 가능성이 있는 경우도 있음.
		//에) 사용자로부터 2개의 정수를 입력받아 나눗셈하는 프로그램
		
		Scanner scan=new Scanner(System.in);
		
//		int n1;
//		int n2;
//		
//		try {
//		 n1=scan.nextInt();
//		 n2=scan.nextInt();
//		 System.out.println("결과: " + n1/n2);
//		 
//		}catch(InputMismatchException e) {
//			 System.out.println("정수만 입력해!!");
//		 }catch(ArithmeticException e){
//			 System.out.println("0나눗셈 문제");
//		 }
		
		//예외의 종류를 모르거나.. 또는 여러 예외를 모두 catch하려면.*********
		try {
			//...
		}catch(Exception e) {
			//모든 xxxException클래스들의 부모클래스************아무거나 다 받을 수 있다.
		}
		//예외가 발생하든 안하는 실행하고 싶은 내용이 있다면..
		try {
			System.out.println("계산 : " +10/0);
		}catch(Exception e) {
			System.out.println("예외");
		}finally {
			System.out.println("여기는 무조건 실행");
		}
		
		//finally를 쓰면 catch문을 생략할 수 있음.
		try {
			
		}finally {
			
		}
		//자바의 기능들 중에서는 필수로 예외처리를 해야만 하는 기능도 있음.
		
		try {
			//URL url=new URL("http://www.naver.com");
			URL url=new URL("www.naver.com");
			System.out.println("접속 성공");
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			System.out.println("접속 못했어요 ㅠㅠ");
		}
		//결국 예외처리 라는 문법은...
		//예외가 발생안하는 것이 아니라.. 발생하더라도..
		//앱이 다운되지 않도록 하는 문법
		
		
		
		
		System.out.println();
		System.out.println("!!프로그램 종료!!");
	}//main method..

}
-----------------------------------------------------------------------------------------
public class Main2 {

	public static void main(String[] args) {
		//throws : 예외 떠넘기기..문법
		
		//throws로 던져진 예외를 대신 처리..
	 try{
		 int n= divide(10,0);
		System.out.println(n);
		
	 }catch(ArithmeticException e) {
		 System.out.println("0나눗셈 불가");
	 }
	 
	}
	  //예외처리는 예외발생가ㅏ능성이 있는 코드에  작성해야함.
	//하지만, 경우에 따라서는 이 메소드안에서 작성하기 곤란한 경우도 있음.
	//이때 예외 처리를 이 메소드를 호출하는 곳에서 대신 하독록 던져버릴수 있음..
	//throws 키워드 : 메소드 이름 옆에 작성..
	static int divide(int x,int y) throws ArithmeticException{
		return x/y;
	}
		
//	static int divide(int x, int y) {
//		try {
//			return x/y;
//		}catch(ArithmeticException e) {
//			System.out.println("0나눗셈 불가");
//			return ???; //뭐라고 써야할지 난감함..
//		}
//		
//	}

}
-------------------------------------------------------------------------------------------
public class Main3 {

	public static void main(String[] args) {
		//throw : 코드를 통해 예외를 강제로 발생시키는 문법
		
		try {
			System.out.println("aaa");
			
			//억지로 예외발생!
			throw new Exception();
			
		}catch (Exception e ) {
			System.out.println("예외 발생!");
		}
		
		//활용 예)
		//연산의 계산결과가 음수가 되는 것이 싫을 때..
		//음수가 나오면 예외라고 처리하게끔 하고 싶을떄..
		int a=10,b=15;
		try {
			int c= a-b;
			if(c<0) throw new Exception("음수 안돼!!");
			
			System.out.println(c);
		}catch(Exception e ) {
			System.out.println("예외발생~~~~"+ e.getMessage());
		}
		

	}

}
 

'JAVA' 카테고리의 다른 글

Collection API: List, Set, Map  (2) 2023.08.30
Generic  (0) 2023.08.30
Object 클래스: 모든 클래스의 (최상위)  (0) 2023.07.15
인터페이스(Interface)  (0) 2023.07.15
추상클래스(abstract), 익명클래스  (0) 2023.07.15