ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • java :: Exception(예외처리)
    IT/Java & JSP & FW 2011. 12. 21. 12:46
    Exception (예외처리)
    예외란?
    프로그램이 진행하는 과정에서 만나게 되는 오류(가벼운 정도의 에러)

    예외처리 목적
    프로그램이 진행 할 때 일으킬 수 있는 상황들을 미리 정해놓고, 해당하는 예외가 발생했을 경우 그에 맞는 적절한 조치를 취해서 프로그램이 정상적으로 작동하도록 하기 위해서이다.

    Exception 상속도 찾아볼 것.

    예외처리방법 (2가지)
    1. Handle 하는 방법
    try~catch 구문을 이용

    형식

    try{

    예외가 발생할만한 코드

     }catch(해당_Exception e){

    예외일시 처리할 루틴


    예제-1
    (ExcepTest.java)
    public class ExcepTest {
    	public static void main(String[] args) {
    
    		try{
    			String str=null;
    			System.out.println("str의 값은:"+str.toString());  //toString 은 오브젝트가 가지고 있다.
    		}catch(NullPointerException e){
    			System.out.println("객체가 없어요.");
    			e.printStackTrace();  //개발자를 위한 키워드, 실제 사용자가 사용할 땐 지워야 한다.
    		}
    		System.out.println("프로그램 정상종료!");
    	}
    }
    
    예제-2
    (ExcepTest2.java)
    public class ExcepTest2 {
    	public static void main(String[] args) {
    		String arr[]={"배", "사과", "포도"};
    		
    		try{
    			for(int i=0;i<=3;i++){
    				System.out.println(arr[i]);
    			}
    		}catch(ArrayIndexOutOfBoundsException e){  //내가 아는 예외발생시 예외 이름을 적는다.
    			System.out.println("배열이 넘었네요.");
    		}
    		
    		System.out.println("=======================");
    		
    		try{
    			for(int i=0;i<=3;i++){
    				System.out.println(arr[i]);
    			}
    		}catch(Exception e){  //Exception으로 지정하면 포괄적인 예외를 잡을 수 있다.
    			System.out.println("배열이 넘었네요.");
    		}
    		
    		System.out.println("프로그램 정상종료");
    	}
    }
    

    하나의 try문과 여러 개의 catch문

    형식

    try{

    예외가 발생할만한 코드

    }catch(해당_Exception e){

    예외일시 처리할 루틴

    }catch(해당_Exception e){

    예외일시 처리할 루틴

    }catch(해당_Exception e){

    예외일시 처리할 루틴

    }


    예제-1
    (ExcepTest4.java)
    //다중 예외 처리 (다중 catch문)
    public class ExcepTest4 {
    	public static void main(String[] args) { //String[] args 문자열의 배열을 의미한다.
    		
    		try{
    			System.out.println("입력된 값A:"+args[0]);
    			System.out.println("입력된 값B:"+args[1]);
    		
    			int num1=Integer.parseInt(args[0]);
    			int num2=Integer.parseInt(args[1]);
    			
    			System.out.println(num1+"/"+num2+"="+(num1/num2));
    		}catch(ArrayIndexOutOfBoundsException e){
    			System.out.println("값을 입력해주세요.");
    		}catch(NumberFormatException e){
    			System.out.println("숫자만 입력해주세요.");
    		}catch(ArithmeticException e){
    			System.out.println("0으로는 나눌수 없어요.");
    		}catch(Exception e){
    			System.out.println("미확인 에러발생");  //마지막은 아버지격인 Exception 클래스로 잡아준다.
    		}
    	}
    }
    
    예제-2
    (ExcepTest5.java)
    import java.io.*;
    public class ExcepTest5 {
    	public static void main(String[] args) {
    		
    		BufferedReader in=
    				new BufferedReader(new InputStreamReader(System.in));
    		
    		try{
    			System.out.print("몇 개의 데이터를 입력하실거에요?");
    			int uesr=Integer.parseInt(in.readLine());
    			int arr[]=new int[uesr];
    			for(int i=0;i<uesr;i++){
    				System.out.print("데이터"+(i+1)+"값=");
    				arr[i]=Integer.parseInt(in.readLine());
    			}
    			
    			System.out.print("출력하고 싶은 값은 몇 번째에 있나요?");
    			int po=Integer.parseInt(in.readLine());
    			System.out.println("선택한 데이터 : "+arr[po-1]);
    
    			
    		}catch(IOException e){
    			System.out.println("입출력관련 오류 발생");
    		}catch(NumberFormatException e){
    			System.out.println("숫자를 입력해 주십시오.");
    		}catch(ArrayIndexOutOfBoundsException e){
    			System.out.println("없는 데이터입니다.");
    		}catch(Exception e){
    			System.out.println("알 수 없는 에러발생");
    		}finally{   //하나의 형식 그대로 외울 것.
    			try{
    				in.close();  //맨 위에서 지정한 Buffered 를 반환시킨다.
    			}catch(Exception e){}
    		}
    	}
    }
    

    finally문 (자원을 반환시킴)
    try ~ catch문에서 예외가 발생하거나 또는 발생하지 않더라도 반드시 실행해야하는 문장이 있을 때 사용하는 구문

    예외처리 미루기
    메소드 내부에서 예외를 직접 처리하지 않고 메소드를 호출한 곳으로 예외처리를 미루는 방법

    예시

    public void sub() throws IOException{}

    의미) 위 처럼 선언하면, sub()을 호출하는 쪽으로 IOException을 넘겨준다.
    RuntimeException계열 예외들은 throws를 안해줘도 JVM이 알아서 throws를 해주므로 생략해도 된다.

    예제
    (ThrowsTest.java)
    import java.io.*;
    // 에러발생시키기
    class AAA{
    	public void aaa() throws IOException{  //thorws를 사용하면 아래줄에서 에러가 나지 않는다.
    		throw new IOException();
    	}
    }
    
    class BBB{
    	public void bbb()throws IOException{
    		AAA a=new AAA();
    		a.aaa();
    	}
    }
    
    public class ThrowsTest {
    	public static void main(String[] args)throws IOException{
    		BBB b=new BBB();
    		b.bbb();
    	}
    }
    //구동해보면 어디서부터 에러가 나서 어디까지 전파가 되었는지 알려준다.
    

    사용자 정의 예외
    사용자가 의도적으로 예외를 발생시키는 것(개발자의 편의성)
    사용빈도는 높지 않다.

    형식

    throw 예외객체
    또는
    throw new 예외클래스(전달인자); 


     예제-1
    (UesrException.java)
    import java.io.*;
    
    //사용자 정의 Exception (새롭게 예외상황을 만듬)
    //많은 예외상황을 공통적으로 묶어줄 때 유용함
    class SeoException extends Exception{  //일반 클래스이지만 상속을 통해 Exception으로 만들 것임
    	public SeoException(){
    		super("에러 : 새롭게 정의된 예외");
    	}
    }
    
    public class UesrException {
    
    	public static void main(String[] args) 
    	throws IOException{
    
    		BufferedReader in=
    				new BufferedReader(new InputStreamReader(System.in));
    		
    		try{
    			System.out.print("너 몇살?");
    			int age=Integer.parseInt(in.readLine());
    			if(age<20){
    				throw new SeoException();
    			}
    			System.out.println("환영합니다.");
    		}catch(SeoException e){
    			System.out.println("20살 미만");
    			e.printStackTrace();
    		}
    	}
    }
    
    예제-2
    (NumException.java)
    import java.io.*;
    
    class NewNumException extends Exception{
    	public NewNumException(){
    		super("숫자를 입력하셨습니다");
    	}
    }
    
    public class NumException {
    	public static void main(String[] args) 
    	throws IOException{
    		
    		System.out.println("숫자 한 자리를 입력하세요");
    		int num=System.in.read();
    		System.out.println("num값:"+num);
    		
    		try{
    			if((num>=48)&&(num<=57)){
    				throw new NewNumException();
    			}else{
    				System.out.println("숫자 한 자리를 입력하시지 않으셨습니다.");
    			}
    		}catch(NewNumException e){
    			System.out.println("숫자입력하셨음");
    			e.printStackTrace();
    		}
    	}
    }
    예제-3
    (ExceptionEx13.java)
    import java.io.FileOutputStream;
    import java.io.PrintStream;
    
    public class ExceptionEx13 {
    
    	public static void main(String[] args) {
    		PrintStream ps=null;
    		FileOutputStream fos=null;
    		
    		try{
    			fos=new FileOutputStream("d:\\error.log");  //저장할 파일이름과 경로
    			ps=new PrintStream(fos);
    			
    			System.out.println(1);
    			System.out.println(2);
    			System.out.println(3);
    			System.out.println(0/0);
    			System.out.println(4);
    			
    		}catch(Exception e){
    			e.printStackTrace();
    			e.printStackTrace(ps);  //파일로 에러메세지를 뽑아냄
    			ps.println("예외메시지:"+e.getMessage());
    		}
    		System.out.println(6);
    	}
    
    }
    
Designed by Tistory.