Jam's story
19일차 본문
내부클래스
- 클래스 내부안에 클래스를 멤버처럼 선언
- 장점
- 접근성- 클래스 맴버+ 내부클래스 호출(내부클래스에서 외부클래스)
- 보안성
class A{ //외부클래스
int x;
int y;
B obj=new B();
//내부클래스
private class B{
외부클래스의 멤버를 자기사진 멤버처럼 자유롭게 접근할 수 있다.
}
}
익명클래스
- 클래스 선언+생성
- 일회성 클래스- 오직 한개의 객체 생성이 된다.
- 익명클래스 선언 형식
new 부모 클래스(){
//필드 x ,
// 부모크래래스의 메소드만 오버라이딩(재정의 ) 할 수 있다.
}
new 인터페이스(){
//인터페이스의 추상메소드만 오버라이딩 할 수 있다.
}
익명클래스
예외처리
발생할 수 있는 에러에 대비한 코드를 작성, 비정상적 종료를 막고 정상적인 실행상태를 유지
- 오류
- 컴파일에러
- 런타임에러
- 에러
- 예외
- try~catch문
- thorws문
- 논리적에러
예외도 상속관계가 있다
다중catch문 vs 멀티 catch문
다중 catch문
try{
}catch(예 e){
}catch(예 e){
}
두 예외가 상속관계라면 부모가 나중에 와야한다.
멀티 catch문
try{
} catch( A예 | B예 e)
두개가 상속관계라면 같이 쓰지 못함
try { 예외가 발생할 수도 있는 문장 } catch (Exception e ){}
try{
//예외가 생길 수 있는 실행문장들
}catch(Exception e){
}catch(Exception2 e2){
}
catch 블럭안에 try-catch 블럭이 포함된 경우, 예외 참조변수가 같으면 안된다.
어떤 오류가 발생할지 모르니, catch괄호에 Exception e 넣고,
실행문에 e.printStackTrace(); 로 어떤 오류가 출력되는지 본다.
저 오류를 catch 괄호에 넣어준다.
try 문에서 예외가 발생하면 try문을 빠져나가고 해당 catch 문으로 들어감
printStackTrace() -> 메소드의 정보와 예외 메세지를 화면에 출력
getMessage() -> 저장된 메세지를 얻을 수 있다.
궁금한거는 왜 exception catch 블록이 실행이 되는지.... ??
public class Prac {
public static void main(String[] args) {
System.out.println("1");
System.out.println("2");
try {
System.out.println("3");
System.out.println(10 / 0);
System.out.println("4");
} catch (ArithmeticException ae) {
if (ae instanceof ArithmeticException )
System.out.println("true");
System.out.println("5");
ae.printStackTrace();
System.out.println(ae.getMessage());
} catch (Exception e1) {
System.out.println("6");
System.out.println("exception");
e1.printStackTrace();
System.out.println(e1.getMessage());
} finally {
System.out.println("7");
}
}// main
}// class
멀티 catch 블럭
catch( 괄호안에 | 를 사용하여 , 형제인것들 사용가능 )
예) catch(Exception | ExceptioneB e)
다중 catch()를 사용할때는 부모 예외 catch문을 제일 나중에 사용
int[] m=new int[3];
try {
m[0]=1;
m[100]=20;
int result=100/0;
System.out.println(result);
}catch(ArrayIndexOutOfBoundsException | ArithmeticException e) {
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
System.out.println("그 밖의 예외가 발생하였다. ");
catch(ArrayIndexOutOfBoundsException | ArithmeticException e)
부모예외클래스| 자식에외클래스 -> 에러발생
(e instanceof ArrayIndexOutOfBoundsException)
instanceof로 예외 구분 가능
try -with- resources 문
try 괄호 안에 객체를 생성하면,try 블럭을 벗어나는 순간 자동으로 자원이 반환된다.
여러개 선언 가능
예외발생시키기
public class Prac {
public static void main(String[] args) {
try {
Exception e =new Exception("고의로 발생시킴");
throw e;
//throw new Exception("고의로 발생시킴");}
catch (Exception e) {
System.out.println("에러메세지:"+ e.getMessage());
e.printStackTrace();
}
System.out.println("프로그램종료 ");
}// main
}// class
생성자에 String을 넣어주면 getMessage()를 통해 얻을 수 있다.
Comments