본문 바로가기

자바

checked Exception

예제1)


import java.io.BufferedReader;

import java.io.InputStreamReader;


public class Test4 {

public static void main(String[] args) throws Exception{

Demo4 ob=new Demo4();

/*try~catch로 예외 잡을 때.

try{

int a;

a=ob.numInput();

System.out.println("입력받은수 : "+ a);

}catch( Exception e){

e.printStackTrace();

}

System.out.println("프로그램 종료");

*/

// throws Exception으로 에러 잡을 때. => 실무에서는 사용하면 안된다.

int a;

a=ob.numInput();

System.out.println("입력받은수 : "+ a);

System.out.println("프로그램 종료");

}

}


class Demo4{

public int numInput() throws Exception{

int n=0;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

try{

System.out.print("수?");

n=Integer.parseInt(br.readLine());

}catch(Exception e){

// 예외를 발생 시킴(  checked exception)

throw new Exception("숫자가 아니므니다.");

}

return n;

}

}


예제1 결과) 수를 입력하지않았을 때

수?w
Exception in thread "main" java.lang.Exception: 숫자가 아니므니다.
at com.test0524.Demo4.numInput(Test4.java:43)
at com.test0524.Test4.main(Test4.java:25)

==============================================================================================================================

예제2)

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Test5 {
public static void main(String[] args) {
int a,b;
char oper; // char oper='\0' => 문자열의 초기화 \0
Demo5 ob=new Demo5();
try{
a=ob.inputNum("첫번째수 ?"); //Demo5의 클래스를 ob의 참조변수를 이용하여 inputNum메서드에 괄호안의 매개변수를 적용하여 호출했다.
b=ob.inputNum("두번째 수?");
oper=ob.inputOper();
if(oper=='+')
System.out.println("합 :" +(a+b));
else if(oper=='-')
System.out.println("차 :" +(a-b));
else if(oper=='*')
System.out.println("곱 :" +(a*b));
else if(oper=='/')
System.out.println("몫 :" +(a/b));
}catch(Exception e){
System.out.println(e.toString());
}
}
}


class Demo5{
private BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public int inputNum(String title) throws Exception {
int n=0;
try{
System.out.println(title);
n=Integer.parseInt(br.readLine());
}catch(Exception e){
throw new Exception("숫자만 입력 가능 합니다.");
}
return n;
}
public char inputOper() throws Exception {
char ch='\0';
System.out.println("연산자 ?");
ch=(char)System.in.read();
System.in.skip(2);
if(ch!='+'&& ch!='-' && ch!='/' &&ch!='*')
throw new Exception("연산자는 + - * / 만 가능합니다.");
return ch;
}
}

결과)

첫번째수 ?
1
두번째 수?
2
연산자 ?
1
java.lang.Exception: 연산자는 + - * / 만 가능합니다.

==============================================================================================================================

예제3)

public class Test6 {
public static void main(String[] args){
Demo6 ob=new Demo6();
try{
int a=ob.getValue(-2);
System.out.println(a);
}catch(Exception e){
System.out.println("main :"+e.toString());
}
System.out.println("종료...");
}
}


class Demo6{
public int getValue(int value) throws Exception{
int n=0;
try{
n=getData(value);
}catch(Exception e){
System.out.println(e.toString());
throw e; //예외를 다시 던저버림
// 그렇지 않으면 main()에서는 에외를 잡지못함
}
return n;
}
public int getData(int data) throws Exception{
if(data<0)
throw new Exception("0보다 적은수...");
return data+10;
}
}

// throw 로 예외를 던지면 catch가 잡는다.
// ↓↓↓↓↓↓↓위 예제 흐름 ↓↓↓↓↓↓↓↓
// test6클래스에서 Demo6의 getvalue메서호출 다시 getvalue에서 getData를 호출하였다.
// getdata클래스에서 if조건에 만족하여 throw 문을 실행하였다. return으로 호출했던 getvalue클래스로 갔다.
// throw를 getdata에서 던졌기때문에 getvalue의 catch가 잡는다. 
// catch 명령문을 실행하고 25번줄 통해서 main클래스까지 throw를 던져서 main클래스의 catch가 실행되어졌다.

예제3 결과)

java.lang.Exception: 0보다 적은수...
main :java.lang.Exception: 0보다 적은수...
종료...

==============================================================================================================================

예제4)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test7 {
public static void main(String[] args) {
Demo7 ob=new Demo7();
String m;
try{
ob.input(); // 여기에 Demo7클래스 private변수들이 담긴다.
m=ob.getMessage();
System.out.println(m);
}catch(Exception e){
System.out.println(e.toString());
}
}
}


class Demo7{
private String name;
private int age;
public void input() throws Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try{
System.out.println("이름은?");
name=br.readLine();
System.out.println("나이는?");
age=Integer.parseInt(br.readLine());
if(age<0)
throw new Exception("나이는 0보다 작을 수 없습니다");
}catch(IOException e){
System.out.println(e.toString());
}catch(NumberFormatException e){
throw new Exception("숫자만 가능!!!");
}
}
public String getMessage(){
String msg=null;
if(name!=null){
msg = name + "님은";
if(age<19)
msg+="미성년자 입니다.";
else
msg+="성인입니다.";
}
return msg;
}
}

예제4 결과)

이름은?
홍길동
나이는?
19
홍길동님은성인입니다.


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

자바에서 session 정보 가져오기  (0) 2013.10.04
재미있는 예제  (0) 2013.05.28
unchecked exception  (0) 2013.05.28
class 클래스  (0) 2013.05.25
replaceAll의 알고리즘  (0) 2013.05.25