package Demo2;

import java.io.FileWriter;
import java.io.IOException;

public class ExceptionDemo1 {

	public static void main(String[] args) {
		
		// 예외 정보 얻기, 출력하기
		try {
			FileWriter writer = new FileWriter("c:/sample.txt");
			writer.write("예외정보 얻기");
			writer.flush();
			writer.close();
		} catch (IOException e) {
			System.out.println("예외 발생!");
			String message = e.getMessage();
			System.out.println("예외 정보 : " + message);
			
			String text = e.toString();
			System.out.println("예외 정보 : " + text);
			
			e.printStackTrace();
		}
	}
}
package Demo2;

public class MyexceptionDemo1 {
	/**
	 * 문자열 배열을 전달받아서 화면에 배열의 내용을 출력하는 메소드
	 * @param names 문자열 배열
	 * @throws MyException 배열이 null이거나 배열의 길이가 0인 경우 예외 발생
	 */
	// 사용자정의 일반예외 <-- Exception 클래스를 상속받으면 일반예외가 된다.
	// 일반예외는 예외처리가 필수다.
	public static void printArray(String[] names) throws MyException {
		if (names == null || names.length == 0) {	// 예외 상황
			throw new MyException("null인 배열이 전달되었습니다.");
		}
		for (String item : names) {
			System.out.println(item);
		}
	}
	public static void main(String[] args) {
		
		String[] teamNames = {"영업팀", "서울팀", "경기팀"};
		String[] studentNames = null;
		try {
			MyexceptionDemo1.printArray(teamNames);
			MyexceptionDemo1.printArray(studentNames);

		} catch (MyException e) {
			e.printStackTrace();
		}
	}
}
package Demo2;

public class MyException extends Exception {
	public MyException() {
		
	}
	
	public MyException(String message) {
		super(message); 			// 예외 정보로 저장된다(Exception의 생성자 호출).
		
	}
}
package Demo2;

// 사용자정의 실행예외 <-- RuntimeException을 상속받으면 실행예외가 된다.
// 실행예외는 예외처리가 선택이다.
public class MyRuntimeException extends RuntimeException {

	public MyRuntimeException() {
		
	}
	
	public MyRuntimeException(String message) {
		super(message);
	}
}
package Demo2;

public class MyRuntimeExceptionDemo1 {

	public static void printArray(String[] items) {
		if (items == null || items.length == 0) {
			throw new MyRuntimeException("배열이 null이거나 길이가 0입니다.");
		}
		
		for (String item : items) {
			System.out.println(item);
		}
	}
	
	public static void main(String[] args) {
		String[] teamNames = {"영업팀", "서울팀", "경기팀"};
		String[] studentNames = null;
		
		MyRuntimeExceptionDemo1.printArray(teamNames);
		MyRuntimeExceptionDemo1.printArray(studentNames);
	}
}

'자바 > exception' 카테고리의 다른 글

demo4  (0) 2019.06.10
demo3  (0) 2019.06.10
demo1  (0) 2019.06.10

+ Recent posts