[Java]/Program source (java)
148, 149 - Java 예외처리(Exception Handling) : IOException과, ArrayIndexOutOfBoundsException의 예외처리를 try~catch(IOException e) catch(ArrayIndex...Exception e) 로 처리하는 프로그램
Jelly-fish
2023. 9. 20. 15:53
/* ============================================
■■■ 예외 처리(Exception Handling) ■■■
=============================================*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Test148
{
private String[] data = new String[3];
public void proc() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
int n = 0; // data[] 배열의 인덱스 값으로 사용할 n.
System.out.print("이름 입력(종료:Ctrl+z) : ");
// br.readLine()으로 갖고오자마자, str에 담은 것이 비어있지 않으면 실행한다.
while ((str=br.readLine()) != null) // str 문자열이 비어있지 않으면... 계속 반복
{
data[n++] = str; // data 배열(길이 : 3)에 n을 1씩 증가시키며 str을 저장 (첫 시작은 0. postfix)
System.out.print("이름 입력(종료:Ctrl+z) : ");
// ★☆★☆★ Ctrl+z 를 입력하면 null 이 된다!!! → 따라서, 입력이 종료된다...
}
System.out.println("입력된 내용 ................");
// data에 들어간 문자열 요소 하나씩을 변수 s에 하나씩 꺼내온다.
// for each 구문
for (String s : data)
{
// 시작하자마자 Ctrl+Z를 하면 data[] 배열에 아무것도 들어있지 않기 때문에
// 출력할 내용이 없으므로.
// null 이 아닐 때만 출력할 수 있도록 처리한 것이다.
if (s != null) // 만약, 문자열이 비어있지 않으면...
{
System.out.println(s); // 문자열 s 를 출력한다.
}
}
}
// BufferedReader 의 readLine() 메소드도... IOException을 사용하는 것!!
// 부모 클래스의 메소드에서 사용하는 예외처리이므로 자식한테까지 넘어간 것이다.
// ArrayIndexOutOfBounds → 런타임 에러이므로 unchecked exception 이다.
// unchecked exception 이므로, 예외처리를 하지 않아도 자바에서 자동으로 컴파일을 시켜준다.
public static void main(String[] args) throws IOException
{
Test148 ob = new Test148();
ob.proc();
}
}
/* ============================================
■■■ 예외 처리(Exception Handling) ■■■
=============================================*/
// 자바가 컴파일 시켜주지 않는 Exception → checked exception
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Test149
{
private String[] data = new String[3];
public void proc() //throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
int n = 0; // data[] 배열의 인덱스 값으로 사용할 n.
try
{
System.out.print("이름 입력(종료:Ctrl+z) : ");
while ((str=br.readLine()) != null)
{
data[n++] = str;
System.out.print("이름 입력(종료:Ctrl+z) : ");
}
System.out.println("입력된 내용 ................");
for (String s : data)
{
if (s != null)
{
System.out.println(s);
}
}
}
catch (IOException e)
{
System.out.println(e.toString());
System.out.println("→ checked exception 에 대한 처리");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("배열 인덱스 관련 예외 발생~!!!");
System.out.println("e.getMessage() : " + e.getMessage());
System.out.println("e.toString() : " + e.toString());
System.out.println("printStackTrace...................");
e.printStackTrace();
}
}
public static void main(String[] args)
{
Test149 ob = new Test149();
ob.proc();
}
}