throwing an exception
이라고 부른다 (예외 던지기) runtime 시스템이 예외를 처리하려고 시도한다.
콜스택
exception handler
)(ex. catch문) 찾는다. catch the exception
했다고 한다. try {
//예외가 발생할 가능성이 있는 코드
} catch (Exception1 e1) {
// Exception1이 발생할 경우, 이를 처리하기 위한 문장
} catch (Exception2 e2) {
// Exception2이 발생할 경우, 이를 처리하기 위한 문장
} catch (Exception3 e3) {
// Exception3이 발생할 경우, 이를 처리하기 위한 문장
} finally {
// 예외 발생여부에 관계없이 항상 수행되어야 하는 문장
}
{}
생략 불가// 일치하는 catch 블럭 찾으면, catch 블럭 내 문장을 수행하고 전체 try-catch문을 빠져나간다
public class TryCatch {
public static void main(String[] args) {
TryCatch tc = new TryCatch();
tc.try_catch();
}
public void try_catch() {
System.out.println(1);
try {
System.out.println(0/0);
System.out.println(2); // 실행되지 않는다
} catch (ArithmeticException ae) {
System.out.println(3);
} finally {
System.out.println(4);
}
}
}
// 결과 1 3 4
발생한예외인스턴스
instanceof
catch문에적힌예외클래스
true
가 나올 때까지 catch안의 () 순차적 확인 |
기호로 하나의 catch 블럭으로 여러 예외 처리 가능하다. 예외 처리 코드가 똑같다면 이렇게 써주면 된다. try {
} catch (ExceptionA | ExceptionB e) {
}
public static void main(String[] args) {
TryCatchFinally tc = new TryCatchFinally();
System.out.println(tc.tryReturn());
} // 결과 in try, in catch, 2
public int tryReturn() {
try {
System.out.println("in try");
int x = 10/0;
return 1;
} catch (ArithmeticException e) {
System.out.println("in catch");
}
return 2;
}
//case1
public int tryFinallyReturn() {
try {
System.out.println("in try");
return 1;
} catch (ArithmeticException e) {
System.out.println("in catch");
return 2;
} finally {
System.out.println("in finally");
return 3;
}
} // 결과 in try, in finally, 3
public int catchFinallyReturn() {
try {
System.out.println("in try");
int x = 10/0;
return 1;
} catch (ArithmeticException e) {
System.out.println("in catch");
return 2;
} finally {
System.out.println("in finally");
return 3;
} // 결과 in try, in catch, in finally, 3
}
//case2
/*
public int notCatch() {
int x = 10 / 0;
return 1;
}
원래 이것을 실행하면 ArithmeticException 발생
*/
public int notCatch() {
try {
int x = 10 / 0;
return 1;
}
finally {
return 42;
}
} //결과 42, 정상종료
public int onlyTryReturn() {
try {
System.out.println("in try");
return 1;
} catch (ArithmeticException e) {
System.out.println("in catch");
} finally {
System.out.println("in finally");
}
return 2;
} //결과 in try, in finally, 1
//값을 미리 저장해두기 때문에 try의 n 값이 출력
public int tryFinallyReturnVariable() {
int n = 0;
try {
System.out.println("in try");
n = 1;
return n;
} catch (ArithmeticException e) {
System.out.println("in catch");
n = 2;
return n;
} finally {
System.out.println("in finally");
n = 3;
}
} //결과 in try, in finally, 1
// 주의. 객체의 주소를 저장하기 때문에, finally 에서 객체에 변화를 준(아래 에서는 element를 바꿔줌) 것은 반영 된다.
public int[] tryFinallyReturnReference2() {
int[] arr = {0,0,0};
try {
System.out.println("in try");
arr = new int[]{1, 1, 1};
return arr;
} catch (ArithmeticException e) {
System.out.println("in catch");
arr[1] = 2;
return arr;
} finally {
System.out.println("in finally");
arr[2] = 3;
arr = new int[]{3, 3, 3};
}
} // 결과 in try, in finally, [1, 1, 3]
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
// java7 이전에 finally를 이용한 close
static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
br.close();
/*
처리해주기 위해
finally {
try { resource.close(); } catch(...) { 아무것도 안 함 }
} 이런 식
*/
}
}
}
void moethod() throws Exception1, Exception2 {
}
public class WithoutThrows {
public static void main(String[] args) {
System.out.println("main");
try {
two();
} catch (ArithmeticException e) {
System.out.println("handle");
}
}
public static void two() {
System.out.println("two");
three(0);
}
public static void three(int n) {
System.out.println("three" + "," + n);
int x = 6 / n;
}
// 결과 : main, two, three,0, handle
public int calculate(int n) {
if (n == 0) {
throw new IllegalStateException();
}
return n * 3;
}
public class ReThrowing {
public static void main(String[] args) {
try {
method();
} catch (Exception e) {
// 해당 예외 처리 2
}
}
public static void method() throws Exception {
try {
throw new Exception();
} catch (Exception e) {
// 해당 예외 처리 1
throw e;
}
}
}
//자바의 정석 예시 case1
public class ChainedException {
public static void main(String[] args) {
try {
method();
} catch (InstallException ie) {
ie.getCause();
}
}
public static void method() throws InstallException {
try {
startInstall(); // SpaceException 발생
copyFiles(): // MemoryException 발생
} catch (SpaceException e) {
InstallException ie = new InstallException("설치중예외발생");
ie.initCause(e);
throw ie;
} catch (MemoryException me) {
}
}
}
super(message)
는 이 예외가 생성될 때 인자로 받는 메세지를 예외의 기본 메세지로 등록 (나중에 getMessage()로 받을)public class NotAuthorizedException extends RuntimeException {
public NotAuthorizedException(String message) {
super(message);
}
}
class Bishal {
} class Geeks {
} class MyClass {
public static void main(String[] args)
{
Object o = class.forName(args[0]).newInstance();
System.out.println("Class created for" + o.getClass().getName());
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
public static void main(String args[]) {
try {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}
class NullPointer_Demo {
public static void main(String args[])
{
try {
String a = null; // null value
System.out.println(a.charAt(0));
}
catch (NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
class NumberFormat_Demo {
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt("akki");
System.out.println(num);
}
catch (NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
class StringIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch (StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}
class Test {
public static void main(String[] args)
{
String s = new String("Geeks");
Object o = (Object)s;
Object o1 = new Object();
String s1 = (String)o1;
}
}
// Java Program to illustrate
// StackOverflowError
class Test {
public static void main(String[] args)
{
m1();
}
public static void m1()
{
m2();
}
public static void m2()
{
m1();
}
}