코드를 완벽하게 짰다고 해서 항상 프로그램이 성공적으로 도는 것은 아닙니다. 다양한 예외 상황이 발생할 수 있는데요. 이것에 대응하기 위해서 예외 처리 코드가 필요합니다.
RuntimeException 실행중에 발생하는 exception을 표현할 때 사용한다.
IOException 파일을 읽고 쓰거나 네트워크 데이터읽고 쓸 때 발생하는 exception을 표현할 때 사용한다.
앞에 ctach나 try가 작동했을 때 아래의 catch내용은 작동하지 않는다
try {
// 예외가 발생할 가능성이 있는 코드를 구현합니다.
} catch (FileNotFoundException e) {
// FileNotFoundException이 발생했을 경우,이를 처리하기 위한 코드를 구현합니다.
} catch (IOException e) {
// FileNotFoundException이 아닌 IOException이 발생했을 경우,이를 처리하기 위한 코드를 구현합니다.
} finally {
// 예외의 발생여부에 관계없이 항상 수행되어야하는 코드를 구현합니다.
// 없어도 되는데 마지막에 항상 실행되어야 하는 코드일 때 여기다가 넣어준다.
// 위에catch문이 작동해도 finally는 실행된다.
}
모든 exception는 getMessage에서 표현된다.
System.out.println("Exception발생: " + e.getMessage());
파일을 생성할 때 원래는 try문 밖에서 쓰면 파일을 열었으니 아래서 닫아줘야한다.
그리고 extends로 IOException을 추가해줘야 한다.
try (FileOutputStream out = new FileOutputStream("test.txt")) {
// test.txt file 에 Hello Sparta 를 출력
out.write("Hello Sparta".getBytes());
out.flush();
} catch (IOException e) {
System.out.println("IOException 발생 : " + e.getMessage());
e.printStackTrace();
}
좀더 긴 try – catch(-finally)문
class ArrayCalculation {
int[] arr = { 0, 1, 2, 3, 4 };
public int divide(int denominatorIndex, int numeratorIndex) {
return arr[denominatorIndex] / arr[numeratorIndex];
}
}
public class Main {
public static void main(String[] args){
ArrayCalculation arrayCalculation = new ArrayCalculation();
System.out.println("2 / 1 = " + arrayCalculation.divide(2, 1));
try{
System.out.println("1 / 0 = " + arrayCalculation.divide(1, 0)); // java.lang.ArithmeticException: "/ by zero"
}catch (ArithmeticException e){
System.out.println("계산이 잘못되었습니다" + e.getMessage());
e.printStackTrace();
}
try{
System.out.println("Try to divide using out of index element = "
+ arrayCalculation.divide(5, 0));
}
catch (ArrayIndexOutOfBoundsException eo){
System.out.println("현재 배열의 index범위는 0부터 " + (arrayCalculation.arr.length -1) + "까지 입니다");
}
}
}
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
System.out.println("now usages");
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
System.out.println(date);//2022-11-14
System.out.println(time);//20:17:49.637
System.out.println(dateTime);//2022-11-14T20:17:49.637
//now()현재시간 말고 특정 시간을 지정할때
//특정날짜를 변수로 설정해서 넣고싶을때 of를 사용한다.
System.out.println("of() usage");
LocalDate dateOf = LocalDate.of(2021,03,30);
LocalTime timeOf = LocalTime.of(22,50,0);
// LocalDateTime dateTimeOf = LocalDateTime();
System.out.println(dateOf);//2021-03-30
System.out.println(timeOf);//22:50 0초일때는 생략된다(초만 생략된다)
}
}
자바 라이브러리에 저장된 SHORT라는 format의 스타일을 가져오는방식
DateTimeFormatter fomatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
String shortFormat = fomatter.format(LocalTime.now());
System.out.println(shortFormat);
자신이 원하는 형식의 스타일을 쓰는방식
//yyyy MM dd 형태같이 정해진 값이 들어가 있고 그 사이에 다른내용을 넣을 수 있다.
// DateTimeFormatter myFomatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
DateTimeFormatter myFomatter = DateTimeFormatter.ofPattern("yyyy년MM월dd일");
String myDate = myFomatter.format(LocalDate.now());
System.out.println(myDate);
FormatStyle의 쓰임 다양한 쓰임새 주소!
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
//Period를 이용하면 기간을 구할수있다.
Period period = Period.between(today,birthday);
//LocalDate.of(연, 월, 일)에서 현재 월수를 적어준 월수에서 뺀다
System.out.println(period.getMonths());
//LocalDate.of(연, 월, 일)에서 현재 일수를 적어준 일수에서뺀다.
System.out.println(period.getDays());
//날짜를 구할때와 오늘의 시간까지 구할때에는 다르게 써줘야 한다.
DateTimeFormatter myFomatterDate = DateTimeFormatter.ofPattern("yyyy/MM/dd h/mm");
//오늘의 날짜만 구할때에는 LocalDate 시간까지 구하면LocalDateTIme으로 써주면된다.
String now = myFomatterDate.format(LocalDateTime.now());
System.out.println("현재시간:"+ now);//현재시간:2022/11/14 8/52