티스토리 뷰
24. 예외처리
: 비교적 가벼운 에러로 에러 발생할것을 미리 예측하여 처리하는것
1. Unchecked Exception : 필요한 경우 예외처리 수행
- ArithmeticException, NullPointException, ArrayIndexOutOfBoundsException
2. Checked Exception : 강제로 예외처리를 수행
- IOException,FileNotFoundException
① throws 예약어 : 예외객체를 양도
<--- 예외상황을 다음 문장으로 전가
② try{ }catch{ } : 예외가 발생하면 예외객체를 잡아내어 원하는 동작을 수행
<-- 예외상황을 처리하고 다음문장 수행
③ try{ }catch{ }finally{ } : 예외가 발생하든 안하든 finally는 무조건수행
[참고] return 을 해도 finally는 수행
④ throw : 예외강제발생
-> 필드에서 가장 많이 씀
Exception : 모든 예외상황
IOException : 입.출력에 관련된 예외
NumberFormatException : 숫자가 아닌 문자가 입력되는 예외
ArithmeticException : 0으로나누는 예외
ArrayIndexOutOfBoundsException : 배열초과
package exeptionex;
public class ExceptionEx1 {
public static void main(String[] args) {
int var=5;
int n = Integer.parseInt(args[0]);
System.out.println(var/n);
}
}
실행하면
java.lang.ArrayIndexOutOfBoundsException:-> main에서 값을 받아와야되는데 없다는 뜻.
마우스 오른쪽 버튼 -> Run as => Run Configurations
Argument -> Variables-> string_prompt -> Run -> 값입력(3) -> 실행 됨.
args[0] 은 0번째 방에서 가져온다는 것
값을 1 0 2 3 4 를 하면 이때 args[0]은 1임.
5/1 이니까 답은 5가 됨.
package exeptionex;
public class ExceptionEx1 {
public static void main(String[] args) {
int var=5;
try { int n = Integer.parseInt(args[0]);
System.out.println(var/n);
}catch(NumberFormatException e) {
System.out.println("숫자로 바꿀 수 없음");
}
}
}
실행시 a를 입력하면 -> "숫자로 바꿀 수 없음 이 뜸.
a는 문자열이니까
package exceptionex;
/*
$ javac ExceptionEx1.java (컴파일)--> ExceptionEx1.class
$ java ExceptionEx1 3 ---> 1
$ java ExceptionEx1 a ---> 숫자로 바꿀수 없습니다
$ java ExceptionEx1 0 ---> 0으로 나눌수 없습니다
$ java ExceptionEx1 ---> 입력값이 없습니다
*/
//unchecked exception
public class ExceptionEx1 {
public static void main(String[] args) {
int var=5;
try {
int n=Integer.parseInt(args[0]);
System.out.println(var/n);
}catch(NumberFormatException e) {
System.out.println("숫자로 바꿀수 없습니다");
}catch(ArithmeticException e) {
System.out.println("0으로 나눌수 없습니다");
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("입력값이 없습니다");
}finally {
System.out.println("무조건 실행");
}
}
}
finally는 어떤걸 넣어도 실행된다.
try {
int n=Integer.parseInt(args[0]);
System.out.println(var/n);
}catch(Exception e) {
System.out.println("오류!!");
}
그냥 Exception은 오류의 종류에 상관 없이 실행됨.
package exceptionex;
//unchecked exception
public class ExceptionEx2 {
public static void main(String[] args) {
int[] num= {10,20,30};
try {
for(int i=0; i<5; i++) {
System.out.println(num[i]);
}
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("배열의 갯수를 초과함");
}
}
}
BufferedReader /
throws IOException
package exceptionex;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/* 클래스명 : ExceptionEx3
*
* str:String
*
* +ExceptionEx3() --> input() 호출
* +input():void --> BufferedReader로 입력받기(Scanner보다 빠름 빠름)
* +output():void --> 출력하기
*
* [출력화면]
* 문자열을 입력하시오 : abcd
* 결과 : abcd
*/
// checked exception
public class ExceptionEx3 {
String str;
public ExceptionEx3() throws IOException {
input();
}
public void input() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("문자열을 입력하세요:");
str = br.readLine();
}
public void output() {
System.out.println("결과: " + str);
}
public static void main(String[] args) throws IOException {
new ExceptionEx3().output();
}
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("문자열을 입력하세요:");
str = br.readLine();
InputStreamReader : 깨지지 않는 글자 하나를 읽어올 때
ex_ 가나다라 => 가/ 나/ 다/ 라 한번씩 4번을 읽어옴
BufferedReader : 엔터칠 때까지 읽어와라 = line단위로 읽어와라
컴파일 상의 에러를 생성자한테 넘기고 이걸 다시 메인한테 넘김 (throws IOException가 3번 나옴) 니가 처리해하고 넘김........
public ExceptionEx3() throws IOException {
...
public void input() throws IOException {
...
public static void main(String[] args) throws IOException {
package exceptionex;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/* 클래스명 : ExceptionEx3
*
* str:String
*
* +ExceptionEx3() --> input() 호출
* +input():void --> BufferedReader로 입력받기
* +output():void --> 출력하기
*
* [출력화면]
* 문자열을 입력하시오 : abcd
* 결과 : abcd
*/
//checked exception
public class ExceptionEx3 {
String str;
public ExceptionEx3() /* throws IOException */
{
input();
}
public void input() /* throws IOException */
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("문자열을 입력하시오:");
try {
str=br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
public void output()
{
System.out.println("결과: " + str);
}
public static void main(String[] args) /* throws IOException */
{
new ExceptionEx3().output();
}
}
사용자정의 예외처리
실행시 java.lang.ArrayIndexOutOfBoundsException:
Run as해 줌
package exceptionex;
//사용자정의 예외처리
class MyException extends Exception{
public MyException() {
System.out.println("입장불가");
}
}
public class ExceptionEx4 {
public static void main(String[] args) throws MyException {
int age=Integer.parseInt(args[0]);
if(age<19) {
throw new MyException();
}else {
System.out.println("고객님 환영합니다");
}
}
}