ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JAVA] Exception(예외처리)
    언어/JAVA 2022. 9. 8. 11:37

    - 에러(Error) : 문법적으로 잘못된 것, 에러가 존재하는 경우 컴파일이 안 되어서 실행자체가 될 수 없음
    - 예외(Exception) : 실행중 발생한 오류, 특정 상황 또는 조건이 만족되는 경우 오류가 발생하여 프로그램이 실행중간에 종료되는 현상

    -예외는 다양한 상황에 대해서 발생하는 현상으로 모든 예외를 대처할 수 없음. 다만, 예외가 발생한 경우 프로그램이 종료되지 않고 저장과 같은 기능을 제공할 수 있어야함. 예외가 발생해도 프로그램이 강제종료되지 않고 사용자에게 선택권 또는 처리기회를 주는것을 말함.
    - 예외처리 : 예외가 발생한 경우 프로그램이 강제 종료되지 않도록 방지 또는 처리하는 것

    public class Exception01 {
    	public static void main(String[] args) {
    		for(int i=1; i<=10; i++) {
    			int k = (int)(Math.random()*10);  //  0~9 사이의 랜덤 정수 발생
    			try {
    				int result = 100 / k;
    				System.out.println(result);
    			}catch( ArithmeticException e) {
    				System.out.println("이번껀은 무효 : 0 으로 나눴습니다.");
    			} // 예외가 발생하면 catch 구문 안의 명령을 대신 실행하고 프로그램 실행을 계속함
    		}
    	}
    }

     

    try 구문안에서 예외가 발생

    - catch의 매개변수에 해당 예외에 해당하는 객체가 있는지 확인하고 있으면 해당 catch 구분을 실행함


    Exception e

    - 모두를 포함, 수용하는 최상위 예외 클래스
    - 다중 예외처리시 가장 마지막에 위치시킴  
    - 다중 예외처리의 표현시 Exception이 가장 위에 있으면, 아래에 위치한 세부적인 예외처리에 순서가 한번도 돌아가지 못하고 Exception에서 모든 예외가 처리됨

    public class Exception02 {
    	public static void main(String[] args) {
    		System.out.println(1);   
    		System.out.println(2);
    		try {
    			 System.out.println(3/0);
    			 System.out.println(4);
    			 // try구문에 있는 명령이라도 에러가 발생한 구문 다음에 위치하는 명령은 실행하지 않음
    		}catch( ArithmeticException e) {
    			e.printStackTrace();   // java.lang.ArithmeticException: / by zero
    			e.getMessage();  // at days32.Exception02.main(Exception02.java:9)
    			System.out.println("5 - 예외처리 1");
    		}catch( Exception e) {
    			System.out.println("5 - 예외처리 2");
    		}
    		System.out.println(6);
    	}
    }
    import java.text.ParseException;
    
    public class Exception03 {
    	public static void main(String[] args) {
    		ArithmeticException a 
    			= new ArithmeticException( "ArithmeticException 고의발생" ); 
    		// a : 예외(오류) 객체
    		try {
    			// 예외(오류)의 강제발생
    			throw a;
    		}catch(ArithmeticException e) {
    			System.out.printf("ArithmeticException - ");
    			System.out.println("에러 메시지 : " + e.getMessage());
    		}catch(RuntimeException e){
    			System.out.printf("RuntimeException - ");
    			System.out.println("에러 메시지 : " + e.getMessage());
    		}catch(Exception e) {
    			System.out.printf("Exception - ");
    			System.out.println("에러 메시지 : " + e.getMessage());
    		}
    		
    		RuntimeException b 
    			= new RuntimeException( "RuntimeException 고의발생" ); 
    		// a : 예외(오류) 객체
    		try {
    			// 예외(오류)의 강제발생
    			throw b;
    		}catch(ArithmeticException e) {
    			System.out.printf("ArithmeticException - ");
    			System.out.println("에러 메시지 : " + e.getMessage());
    		}catch(RuntimeException e){
    			System.out.printf("RuntimeException - ");
    			System.out.println("에러 메시지 : " + e.getMessage());
    		}catch(Exception e) {
    			System.out.printf("Exception - ");
    			System.out.println("에러 메시지 : " + e.getMessage());
    		}
    		
    		ParseException c = new ParseException("ParseException 고의발생", 0);
    		try {
    			throw c; 
    		}catch(ArithmeticException e) {
    			System.out.printf("ArithmeticException - ");
    			System.out.println("에러 메시지 : " + e.getMessage());
    		}catch(RuntimeException e){
    			System.out.printf("RuntimeException - ");
    			System.out.println("에러 메시지 : " + e.getMessage());
    		}catch (ParseException e) {
    			e.printStackTrace();
    		}catch(Exception e) {
    			System.out.printf("Exception - ");
    			System.out.println("에러 메시지 : " + e.getMessage());
    		}
    	}
    }


    throws Exception 꼬리표가 붙은 메서드를 호출
    - 호출하는 지점에 빨간줄(에러)표시가 표시됨. 그럼 다시 add throw declaration/surround with try-catch  중 하나를 선택할 수 있음

     

    throw new Exception()

    - 강제 예외 발생 
    - 예외가 발생할테니 처리하라 라는 의미의 빨간줄이 생김

    public class Exception04 {
    	public static void main(String[] args) {
    		try {
    			method1();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    	public static void method1() throws Exception {
    		method2();
    		/*try {
    			method2();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}*/
    	}
    
    	// 현재 예외처리를 해결하는 방법 #2
    	// add throw declaration 메뉴 사용
    	// "현재 메서드의 명령중에는 에러(예외)가 발생하는 명령이 포함되어 있습니다"
    	// 라고 메서드에 꼬리표( throws Exception)를 붙임
    	private static void method2() throws Exception {
    		throw new Exception();
    		
    		// 현재 예외처리를 해결하는 방법 #1
    		/*try {
    			throw new Exception();
    		} catch( Exception e) {
    			
    		}*/
    	}
    }

     

    날짜 입력

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Scanner;
    
    public class Exception05 {
    	public static void main(String[] args) {
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    		/*String d = "2022/05/12";
    		try {
    			Date today = sdf.parse(d);
    		} catch (ParseException e) {
    			e.printStackTrace();
    		}*/
    		Scanner sc = new Scanner(System.in);
    		String inString = "";
    		Date inDate = null;
    		
    		System.out.print("날짜를 예와 같이 입력해주세요.(입력 예 : 2015-12-31) : ");
    		while(true) {
    			try {
    				inString = sc.nextLine();
    				inDate = sdf.parse(inString);
    				break;
    			} catch (ParseException e) {
    				System.out.print("예와 같이 다시 입력해주세요.(입력 예 : YYYY-MM-DD) : ");
    			}
    		}
    		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy년 MM월 dd일");
    		System.out.println(sdf2.format(inDate));
    	}
    }

     

    자료형이 다르면 다시 입력

    import java.util.InputMismatchException;
    import java.util.Scanner;
    
    public class Exception06 {
    	public static void main(String[] args) {
    		// 순수한 아라비아기호로  문자열을 입력받아서 숫자로 변환하는 코드를 작성
    		// 입력내용중 숫자가 아닌 다른것이 입력되면 
    		// 다시입력하라는 메세지와 함께 입력받는 코드가 실행되게 함
    		// 주요코드 : num = Integer.parseInt( sc.nextLine() ); 
    		// Integer.parseInt() : 숫자가 아닌 글자를 정수로 변환하려고 하면 예외가 발생
    		// 최종 출력 : "입력한 숫자는 XX 입니다"  
    		
    		Scanner sc = new Scanner(System.in);
    		int num = 0;
    		System.out.print("정수를 입력하세요 : ");
    		/*while(true) {
    			try {
    				num = Integer.parseInt( sc.nextLine() );
    				break;
    			} catch(NumberFormatException  e) {
    				System.out.printf("정수가 아닌 잘못된 타입이 입력되었습니다. 재입력 : ");
    			}
    		}
    		*/
    		
    		while(true) {
    			try {
    				num = sc.nextInt();
    				break;
    			} catch(InputMismatchException e) {
    				System.out.println("정수가 아닌 잘못된 타입이 입력되었습니다.");
    				// 키보드 버퍼에 남아있는 문자열(엔터 등)의 값을 제거
    				sc.nextLine(); // 입력 버퍼를 비움
    			}
    		}
    		System.out.println("입력 값 : " + num);
    	}
    }

     

    import java.io.File;
    import java.io.IOException;
    
    public class Exception07 {
    	static int cnt = 0;
    	public static void main(String[] args) {
    		File f1 = createFile("");
    		File f2 = createFile("abc.txt");
    		File f3 = createFile("");
    	}
    
    	public static File createFile(String fileName) {
    		File f = null;
    		// 전달받은 파일이름을 이용하여 파일을 생성후 파일 객체를 리턴
    		try {
    			if( fileName==null || fileName.equals("") )
    				throw new IOException("파일이름이 유효하지 않습니다" );
    		}catch( IOException e) {
    			fileName = "제목없음" + ++cnt + ".txt";
    		}catch( Exception e) {
    			e.printStackTrace();
    		}finally {
    			// 예외가 생겼든 안생겼든 실행되는 영역
    			f = new File(fileName);
    			try {
    				f.createNewFile();  // 파일이 저장장체 실제로 생성됨.  예외처리 발생
    			} catch (IOException e) {
    				e.printStackTrace();
    			} 
    		}
    		return f;
    	}
    }

    '언어 > JAVA' 카테고리의 다른 글

    [JAVA] Swing  (1) 2022.09.08
    [JAVA] Thread  (0) 2022.09.08
    [JAVA] Interface  (3) 2022.09.08
    [JAVA] Abstract(추상클래스)  (0) 2022.09.08
    [JAVA] Formatter  (0) 2022.09.08

    댓글

Designed by Tistory.