2020.09.23 기초 자바 프로그래밍 예외발생 try catch

코딩팩토리 블로그 : https://coding-factory.tistory.com/280 

 



package h_exception;


import java.io.IOException;


public class ThrowsException {


public static void main(String[] args) {

/* 

* 예외 발생시키기

* -throw new Exception(); throw 는 예약어.  

* throw 예약어와 예외 클래스의 객체로 예외를 고의로 발생시킬 수 있다. 

*/

IOException ioe = new IOException(); 

try {

throw ioe;

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

-----------------------------------------------------------------------------------------------------
package h_exception;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ThrowsException_ {
public static void main(String[] args) {
/* 
* 메서드 예외 선언하기 ( 이 메서드를 호출하면 이런예외가 발생할 수 있습니다라고 선언 ) 
* - 메서드 호출 시 발생할 수 있는 에외를 선언해줄 수 있다.
* - void method()throws IOException{}
* - 메서드의 구현부 끝에 throws 예약어와 예외 클래스명으로 예외를 선언할 수 있다. 
* - 예외를 선언하면 예외처리를 하지 않고 자 신을 호출한 메서드로 예외처리를 넘겨준다. 
*/
try {
method () ;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//위에가 예외처리를 넘겨받은것. 
try {
new FileInputStream("");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

private static void method() throws IOException //예외를 선언해주면  
{
throw new IOException();
//예외처리를 하지 않고 넘겨줄 수 있다. 
}
}

댓글