주말이다
하는거 없이 빈둥될까 하다가
독서실로 나와서 멍때리다가
일하다가 그냥 들어가기
뭐해서 복습 겸 쓰고 있다
마감시간이 새벽 1시라는건
정말 슬픈일이 아닐수 없다
더 나를 슬프게 하는건
불쌍한 고딩들이 마감까지도
가지않고 열심히 한단거다
내가 말하고 싶은 슬픔은
얘네가 처한 현실이 아니고
늦게 가서 내가 더 늦게
마감을 할수밖에 없는것이다
쓰레기 같이 볼수도 있겠지만
걔네가 성공한다고 나한테
이득될건 없지 않은가
나는 나대로 열심히 해야 한다
그러니 오늘도 복습을 해보자
import java.util.Scanner;
class OutOfRangeException extends Exception {
public OutOfRangeException() {
super("범위를 벗어난 값입니다.");
}
public OutOfRangeException(String msg) {
super(msg);
}
}
class ExceptionEx1 {
public static void inputAge() throws Exception {
Scanner scan = new Scanner(System.in);
System.out.print("나이를 입력하시오(18~99) : ");
int age = scan.nextInt();
if(age < 18 || age > 99) {
// 예외상황발생
OutOfRangeException e = new OutOfRangeException(
"나이는 18~99세 까지 입력가능합니다."
);
// 예외발생 시키기
throw e;
} else {
System.out.println("칭찬해요");
}
}
public static void main(String[] args) {
try {
inputAge();
} catch(OutOfRangeException e) {
System.out.println("잘못입력했어요~");
System.out.println(e.getMessage());
}
}
}
예외를 어디서 처리하는 위치를
설명해주고 있는 예제이다
우리가 전 포스팅에서 알아냈듯이
그 해당 메소드에서 명시해줄수도 있지만
throws를 이용하여 try-catch문을 적을
곳을 다른곳으로 바꿀수도 있다
한마디로 책임을 전가할수 있다는것
그 위치는 호출한 곳이라 할수 있다
지금 예제에서는 main문에서
예외 처리를 해주고 있는 걸 볼수 있다
사람마다 스타일이 다르기 때문에
나중에 협업을 할때를 대비하여
잘 알아두는것이 좋다
물론, 난 겪어보지 못했다
업으로 먹고 살 생각은 전혀 없으니 말이다
import java.util.*;
class LolitaException extends Exception {
public LolitaException() {
super("은팔찌가 채워져요~");
}
}
class Human {
public static final int ADULT_AGE = 20;
private String name;
private int age;
private Vector<String> confirmedNames;
public Human(String name, int age) {
setName(name);
setAge(age);
confirmedNames = new Vector<String>();
confirmedNames.add("XX두");
confirmedNames.add("윤XX");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void love(Human lover) throws LolitaException {
// 사랑하는 사람이 미성년자인 경우 문제가 발생한다.
if(lover.getAge() < ADULT_AGE && !confirmedNames.contains(name)) {
throw new LolitaException();
} else {
System.out.println(name + " ♡ " + lover.getName());
}
}
}
class ExceptionEx2 {
public static void main(String[] args) {
Human h1 = new Human("김유정", 18);
Human h2 = new Human("X영욱", 40);
Human h3 = new Human("XX두", 39);
try {
h2.love(h1);
} catch(LolitaException e) {
System.out.println(h2.getName() + " : " + e.getMessage());
}
try {
h3.love(h1);
} catch(LolitaException e) {
System.out.println(e.getMessage());
}
}
}
그렇다면 예외를 직접 설정할수 없을까?
당연히 당연하다
자신이 생각하는 예외를 만들어낼수 있다
위의 예제는 성범죄자의 기준을
나이로 정하여 예외처리 하고 있다
당신이 김유정 팬이라면 속상할법도 하지만
이것은 가상의 예제일뿐이니
너무 기분 나빠할 필요도 없고
코드에 집중해주길 바란다
그리고 x영욱 팬은 있을지 모르겠지만
음 뭐 가상일뿐이니 이해해주길 바란다
import java.util.*;
class ExceptionEx5 {
public static void main(String[] args)
throws ArrayIndexOutOfBoundsException,
NumberFormatException, NegativeArraySizeException{
try {
// ArrayIndexOutOfBoundsException
// NumberFormatException
// NegativeArraySizeException
int num = Integer.parseInt(args[0]);
Scanner scan = new Scanner(System.in);
int[] arr = new int[scan.nextInt()];
/*
순차적으로 catch를 검사한다.
상위 예외는 마지막으로~
*/
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("예외발생1");
} catch(NumberFormatException nfe){
System.out.println("예외발생2");
} catch(NegativeArraySizeException e) {
System.out.println("예외발생3");
} catch(Exception e) {
}
}
}
이번에는 여러가지 예외들을
순차적으로 명시해두면 어떻게
될지 보여주고 있다
결과적으로 말하면 순서대로 catch를
검사하고 발생하면 정의해준 대로
결과가 나타나게 될것이다
주의할것은 상위의 예외는
가장 마지막에 적어줘야할것이다
예제에서 Exception을 가장 마지막에
적어준것 처럼 말이다
/*
public class FileReader ... {
public FileReader(String fileName) throws FileNotFoundException {
...
// FileNotFoundException 발생할 수 있음.
}
}
*/
import java.io.*;
class ExceptionEx6 {
public static void second() {
Reader r = null;
try {
r = new FileReader("data.dat");
} finally {
r.close(); // 자원해제
}
}
public static void first() {
try {
second();
} catch(Exception e) {
System.out.println("A");
}
}
public static void main(String[] args) {
try {
second();
} catch(Exception e) {
System.out.println("B");
}
}
}
후에 복습하게 될 파일입출력에
대한 예외처리문이다
그냥 쭈욱 한번 보길 권한다
다음을 위해서 말이다
벌써 새벽 1시반이 되어간다
난 가서 코 자야겠다
당신도 주말이라고 불태우지말고
건강을 위해서 일찍 자길 권해본다
'IT > 자바' 카테고리의 다른 글
자바 과제 복습 (0) | 2017.05.30 |
---|---|
String 문자열에 관한 고찰 (0) | 2017.05.29 |
자바 Exception 예외 처리 (0) | 2017.05.25 |
Map과 HashCode (0) | 2017.05.24 |
Wrapper 클래스 BinarySearch (0) | 2017.05.23 |
댓글