(예제1)
String[]str= {"apple","banana","strawberry","kiwi"};
System.out.println("***차례대로 출력***");
for(int i=0;i<=str.length;i++)
{
try {
//익셉션이 발생할 수 있는 코드
System.out.println(str[i]);
}catch (ArrayIndexOutOfBoundsException e) {
//익셉션이 발생시 실행할 코드
System.out.println("배열요구: "+e.getMessage());
}
}
System.out.println("***거꾸로 출력***");
for(int i=str.length;i>=0;i--)
{
try {
System.out.println(str[i]);
}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("거꾸로 출력 중에 오류:"+e.getMessage());
}
}
//결과
***차례대로 출력***
apple
banana
strawberry
kiwi
배열요구: Index 4 out of bounds for length 4
***거꾸로 출력***
거꾸로 출력 중에 오류:Index 4 out of bounds for length 4
kiwi
strawberry
banana
apple
~~~~~~~~~~~~~~~~~~~~
(예제2)
//thread..무조건 try/catch 작업해줘야함
System.out.println("안녕..3초 뒤에 헤어지자");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("안녕히 계세요ㅠ");
//결과
안녕..3초 뒤에 헤어지자
안녕히 계세요ㅠ
~~~~~~~~~~~~~~~~~~~~
(예제3)
public class ExceptionEx03 {
//throws: 호출한 영역으로 예외처리를 던짐
//throw: 강제로 예외를 발생시킬 때
public static void scoreInput() throws Exception { //호출한 곳으로 throws 던짐
Scanner sc=new Scanner(System.in);
int score=0;
System.out.print("점수 입력: ");
score=Integer.parseInt(sc.nextLine());
if(score<0 || score>100) //점수가 0~100 아니라면 강제로 익셉션 발생
throw new Exception("점수가 잘못 입력되었어요");
else
System.out.println("나의 점수는 "+score+"점 입니다");
}
public static void main(String[] args) {
try {
scoreInput();
} catch (Exception e) {
System.out.println("오류메세지: "+e.getMessage());
}
}
}
//결과
점수 입력: 108
오류메세지: 점수가 잘못 입력되었어요
점수 입력: 90
나의 점수는 90점 입니다
~~~~~~~~~~~~~~~~~~~~
(예제4)
public class ExceptionEx04 {
public static void process() {
int[]arr= {5,20,7,18,2};
for(int i=0;i<=arr.length;i++)
{
try {
System.out.println(arr[i]);
}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("오류메세지1: "+e.getMessage());
}
}
}
public static void main(String[] args) {
process();
}
}
//결과
5
20
7
18
2
오류메세지1: Index 5 out of bounds for length 5
~~~~~~~~~~~~~~~~~~~~
(예제4-1)
//익셉션 처리를 직접하지 않고 호출한 곳으로 넘기기
public static void process2() throws NumberFormatException{
String a="15a";
String b="77";
int sum=0;
sum=Integer.parseInt(a)+Integer.parseInt(b);
System.out.println("두 수의 합은 "+sum);
}
public static void main(String[] args) {
try {
process2();
} catch (NumberFormatException e) {
System.out.println("예외처리를 메인에서 함: "+e.getMessage());
}
System.out.println("정상종료");
}
}
//결과
예외처리를 메인에서 함: For input string: "15a"
정상종료
~~~~~~~~~~~~~~~~~~~~
(예제5)
public class ExceptionEx05 {
public static void process() {
Scanner sc=new Scanner(System.in);
int su1,su2;
System.out.println("두 수 입력");
su1=sc.nextInt();
su2=sc.nextInt();
try {
System.out.println("su1/su2= "+su1/su2);
} catch (ArithmeticException e) {
System.out.println("0으로 나누는 건 불가능: "+e.getMessage());
}finally { //파일 열 때 사용, 지금은 안 해도 되나 한번 해보기
System.out.println("이 영역은 예외 상관없이 무조건 실행");
}
}
public static void main(String[] args) {
process();
//결과
두 수 입력
5
2
su1/su2= 2
이 영역은 예외 상관없이 무조건 실행
~~~~~~~~~~~~~~~~~~~~
(예제5-1)
public static void process2() throws NullPointerException {
Random r=null;
int rnd=r.nextInt(10); // 0~9까지의 난수 발생
System.out.println("발생한 난수: "+rnd);
}
public static void main(String[] args) {
try {
process2();
}catch (NullPointerException e) {
System.out.println("메인에서 예외처리함 "+e.getMessage());
}
System.out.println("정상종료");
}
//결과
메인에서 예외처리함 null
정상종료
~~~~~~~~~~~~~~~~~~~~
(예제6)
class UserException extends Exception{
public UserException(String msg) {
super(msg); //Exception클래스의 생성자를 통해 정식메세지로 등록
}
}
public class ExceptionEx06 {
public static void process() throws UserException {
Scanner sc=new Scanner(System.in);
int age=0;
//나이가 5~80 아니면 UserException 강제발생
System.out.println("나이 입력");
age=sc.nextInt();
if(age<5 || age>80)
throw new UserException("멤버연령은 5~80세");
else
System.out.println("당신은 "+age+"세 이므로 멤버등록!");
}
public static void main(String[] args) {
try {
process();
} catch (UserException e) {
System.out.println("메세지: "+e.getMessage());
}
System.out.println("정상종료");
}
}
//결과
나이 입력
26
당신은 26세 이므로 멤버등록!
정상종료
나이 입력
90
메세지: 멤버연령은 5~80세
정상종료
~~~~~~~~~~~~~~~~~~~~
(예제7)
class UserException2 extends Exception{
public UserException2(String message) {
super(message); //오류메세지를 부모에게 보냄
}
}
public class ExceptionEx07 {
public static void nameInput() throws UserException2{
Scanner sc=new Scanner(System.in);
//억지로 금지단어
String[]str= {"광고","쇼핑","금융","가입"};
String word1="";
System.out.println("단어 입력");
word1=sc.nextLine();
for(String s:str) //대입하겠다는 의미
{
if(s.equals(word1))
{
throw new UserException2("금지된 단어");
}
}
System.out.println("입력한 단어는 "+word1 +"입니다");
}
public static void main(String[] args) {
try {
nameInput();
} catch (UserException2 e) {
System.out.println("오류메세지: "+e.getMessage());
}
}
}
//결과
단어 입력
고양이
입력한 단어는 고양이입니다
단어 입력
광고
오류메세지: 금지된 단어
'JAVA' 카테고리의 다른 글
210819_filereader+bufferreader+split+tokenizer (0) | 2021.08.19 |
---|---|
210819_split+tokenizer (0) | 2021.08.19 |
210818_Exception (0) | 2021.08.18 |
210818_익명내부클래스+상속 (0) | 2021.08.18 |
210818_익명내부클래스 (0) | 2021.08.18 |