public class NullPointerExceptionExample{
public static void main(String[] args){
String data = null;
System.out.println(data.toString());
}
}
public class ArrayIndexOutOfBoundsExceptionExample{
public static void main(String[] args){
String data1 = args[0];
String data2 = args[1];
System.out.println("args[0]: " + args[0]);
System.out.println("args[1]: " + args[1]);
}
}
→ 실행 매개값을 주지 않았기 때문에 args[0], args[1]과 같이 인덱스를 사용할 수 없다.
public class NumberFormatException{
public static void main(String[] args){
String data1 = "100";
String data2 = "a100";
int value1 = Integer.parseInt(data1);
int value2 = Integer.parseInt(data2); //NumberFormatException 발생
int result = value1 + value2;
System.out.println(data1 + "+" + data2 + "=" + result);
}
}
Animal animal = new Dog();
if(animal instanceof Dog){
Dog dog = (Dog) animal;
}else if(animal instanceof Cat){
Cat cat = (Cat) animal;
}
💡 ClassCastException을 발생시키지 않으려면 타입 변환 전에 타입 변환이 가능한지 instanceof 연산자로 확인하는 것이 좋다.
try{
//예외 발생 가능 코드
} catch(예외클래스 e){
//예외 처리
} finally {
//항상 실행;
}
try{
//ArrayIndexOutOfBoundException 발생
//NumberFormatException 발생
} catch(ArrayIndexOutOfBoundException e){
//예외 처리 1
} catch(NumberFormatException e){
//예외 처리 2
}
try{
//ArrayIndexOutOfBoundException 발생
//NumberFormatException 발생
} catch(Exception e){
//예외 처리1
} catch(ArrayIndexOutOfBoundException e){
//예외 처리2 (X)
}
-> 수정된 코드
try{
//ArrayIndexOutOfBoundException 발생
//NumberFormatException 발생
} catch(ArrayIndexOutOfBoundException e){
//예외 처리1
} catch(Exception e){
//예외 처리2
}
→ 수정된 코드는 ArrayIndexOutOfBoundException가 발생하면 첫 번째 catch 블록을 실행하고, 그 밖의 다른 예외가 발생하면 두 번째 catch 블록을 실행한다.
try{
//ArrayIndexOutOfBoundException 또는 NumberFormatException 발생
// 다른 예외 발생
} catch(ArrayIndexOutOfBoundException | NumberFormatException e){
//예외 처리1
} catch(Exception e){
//예외 처리2
}
FileInputStream fis = null;
try{
fis = new FileInputStream("file.txt");
...
}catch(IOException){
...
}finally{
if(fis != null){
try{
fis.close();
}catch(IOException e){
}
}
//자바 6까지 사용했던 코드
try-with-resource를 사용하기 위한 조건
리턴타입 메소드명(매개변수, ...) throws 예외클래스1, 예외클래스2, ...{
}
// 발생할 수 있는 예외 종류별로 throws 뒤에 나열하는 것이 일반적이지만 Exception으로 대체할 수도 있다.
리턴타입 메소드명(매개변수, ...) throws Exception {
}
public void method1(){
try{
method2();
}catch(ClassNotFoundException e){
//예외 처리 코드
System.out.println("클래스가 존재하지 않습니다.");
}
}
public void method2() throws ClassNotFoundException { //호출한 곳에서 예외 처리
Class clazz = Class.forName("java.lang.String2");
}
public class XXXException extends [Exception | RuntimeException]{
public XXXException(){}
public XXXException(String message){super(message);}
}
throw new XXXException();
throw new XXXException("메시지");
} catch(Exception e){
String message = e.getMessage();
}