자바 무료강의 2시간 완성을 시청하고 간략히 정리
프로그램 도중 발생가능한 문제 상황 처리
try{
명령문;
}catch(e){
에러 대응 명령문;
}
public class Main {
public static void main(String[] args) {
int[] num = {1,2,3};
int index = 5; // 존재하지 않는 인덱스
try{
int result = num[index];
System.out.println("result : "+result);
}catch (Exception e){
System.out.println("문제 발생 :"+e);
}
}
}
// 문제 발생 :java.lang.ArrayIndexOutOfBoundsException: 5
예외의 종류에 따라 처리
try{
명령문;
}catch(e1){
에러 처리 명령문 1;
}catch(e2){
에러 처리 명령문 2;
}
public class Main {
public static void main(String[] args) {
int[] num = {1,2,3};
int index = 5; // 존재하지 않는 인덱스
try{
int result = num[index];
System.out.println("result : "+result);
}catch (ArrayIndexOutOfBoundsException e){ // 예외 종류 별 처리
System.out.println("인덱스 :"+e);
}catch (Exception e){
System.out.println("문제 발생 :"+e);
}
}
}
의도적으로 예외 상황 만들기
throw new 예외();
public class Main {
public static void main(String[] args) {
try{
int age = -5;
if(age < 0 ){
throw new Exception("나이는 음수 일 수 없습니다.");
}
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
try 문이 끝나면 항상 실행되는 코드
일반적으로 try 에 사용되는 코드(변수)를 정리, 해제할 때 사용함.
try{
명령문;
}catch(e1){
에러 처리 명령문 1;
}finally{
명령문;
}
public class Main {
public static void main(String[] args) {
try{
int age = -5;
if(age < 0 ){
throw new Exception("나이는 음수 일 수 없습니다.");
}
}catch (Exception e){
System.out.println(e.getMessage());
}finally {
System.out.println("끝!");
}
}
}
// 나이는 음수 일 수 없습니다.
// 끝!
리소스 관리를 편하게 할 수 있는 방법
try(자원){ // 자원이 자동으로 해제
명령문;
}catch(e1){
에러 처리 명령문 1;
}
public class Main {
public static void main(String[] args) {
try(FileWriter writer = new FileWriter("file.text")){ // 자원 할당
writer.write("안녕!");
}catch (Exception e){
System.out.println(e.getMessage());
}finally {
System.out.println("끝!");
}
}
}
개발자가 직접 정의한 예외
class 클래스명 extends Exception{ // 예외 클래스를 상속하여 생성
}
public class Main {
public static void main(String[] args) {
try{
int age = -5;
if(age < 0 ){
throw new MyException("나이는 음수 일 수 없습니다.");
}
}catch (MyException e){
System.out.println(e.getMessage());
}finally {
System.out.println("끝!");
}
}
}
class MyException extends Exception{
public MyException(String message){
super(message);
}
}
메소드를 수행하다 문제가 발생했을 때, 메소드를 호출한 곳에서 처리
반환형 메소드면() throws 예외{
명령문;
}
public class Main {
public static void main(String[] args) {
try{
divide(3,0);
}catch (Exception e){
System.out.println("0으로 나눌 수 없음");
}finally {
System.out.println("끝!");
}
}
public static int divide(int a, int b) throws Exception{
return a/b;
}
}