오류 중에 개발자가 예측해서 제어할 수 있는 오류
컴파일 및 로직상의 문제는 없지만 사용자의 입력 혹은
타 프로그램의 결과에서 예상치 못한 값을 받아 처리할 때 발생
public class ExceptionHandling {
// throws 예외 클래스 : 해당 예외를 호출부로 책임을 전가
// throws가 선언부에 추가된 메서드를 호출하는 곳에서
// 예외 처리에 대한 강제성이 부여된다.
🟡private static void bringException() throws Exception{
Exception exception = new Exception("예외 던지기 발생!");
throw exception;
}
public static void main(String[] args) {
// 예외 상황
// Scanner scanner = null;
// scanner.nextLine(); //오류가 뜬다.
// int[] numbers = {1, 2, 3};
// System.out.println(numbers[4]);
//numbers에는 인덱스 4번째값이 없다. 오류!
예외를 예상하고 그 상황에 대해서 적절한 대처를 해주는것
가장 좋은 것은 예외가 발생하지 않도록 하는 것!
try 구문에 예외가 발생 할 수 있는 문장을 작성
catch 구문에 해당 예외 상황에 대한 대처 구문을 작성
//사용 방법
// try { 예외가 발생할 수 있는 문자 }
// catch (예외타입 예외참조변수){예외가 발생했을 때 처리할 문장}
Scanner scanner = null;
try {
int number = scanner.nextInt();
} catch (Exception exception) {
//NullPointerException의 부모 클래스가 RuntimeException
//RuntimeException의 부모 클래스가 Exception
//(Exception:'예외상황'에 대한 최상위 클래스)
System.out.println("Null Pointer Exception 발생!");
//scanner이 null값이면 오류가 뜨기때문에
//이런 예외사항을 잡아주는데 catch 문 쓴다.
}
//모든 예외 상황을 하나하나 다 알수가 없다!
//Exception으로 받아 처리해주면 된다.
try {
// Exception class로 예외 생성
Exception exception = new Exception("고의 예외!");
// 인스턴스를 만들어주고🤔
// throw로 예외를 발생
throw exception;
} catch(Exception exception){
exception.printStackTrace();
//콘솔창에 오류문구 뜨게 할 수있다
}
//throws 호출해서 오류 뜨게된다.
//bringException(); 예외처리에 대한 강제성 부여
//오류가 뜨게 되는데 처리방법 중 하나인 try catch문으로 감싼것
🟡try {
bringException();
} catch (Exception e) {
e.printStackTrace();
}
//입력한 값이 오류가 될 때를 대비해
//오류일 경우 입력값의 타입이 맞지않습니다를 출력하고
//프로세스 종료하게 한다.
try {
System.out.println("넣을 화폐 : ");
exchangingCurrency = scanner.nextLine(); //넣을 화폐 단위
System.out.println("바꿀 화폐 : ");
exchangedCurrency = scanner.nextLine(); // 바꿀 화폐 단위
System.out.println("금액 : ");
amount = scanner.nextInt(); // 돈
}catch(Exception exception) {
//exception.printStackTrace(); //이렇게 하면 오류로 콘솔에 출력된다.
System.out.println("입력값의 타입이 맞지않습니다.");
return;
}
try-catch 문에 선택적으로 finally라는 구문을 추가
오류가 발생하든 하지 않든 간에 상관없이 무조건 실행되는 구문
외부와의 연결을 종료하는 작업에 주로 사용됨
try {
// 예외 발생할 가능성이 있는 문장들
} catch(예외1) {
// 예외 1에 알맞은 처리
} catch(예외2) {
// 예외 2에 알맞은 처리
} finally {
// 예외 여부와 관계없이 실행되는 부분
}
//finally 문 안쓰면 동일 구문을 각각 try와 catch에 넣어줘야함
try {
System.out.println("외부로 접속");
int c = b/a;
System.out.println("연결 해제");
} catch(ArithmeticException e) {
System.out.println("오류가 발생하였습니다.");
System.out.println("연결 해제")
}
//finally문 쓴 경우
try {
System.out.println("외부로 접속");
int c = b/a;
} catch(ArithmeticException e) {
System.out.println("오류가 발생하였습니다.");
} finally {
System.out.println("연결 해제")
}
로직상 흐름에 벗어나지 않는다면 굳이 finally문 쓰지 않고 다음 구문을 써줄수있다
throw통해 예외를 발생시키고
throws는 예외를 밖으로 던진다 (throws 구문에서는 try-catch 감싸지않는다.)
Java 자체에서 제공해주는 개발에 도움을 주는 각종 라이브러리
public class ApiClass {
public static void main(String[] args) {
//1️⃣Object Class
// 모든 class의 조상 class
Object object = new Scanner(System.in);
object = new int[10]; //모든걸 다 받을 수 있다.
//2️⃣String class
// 문자열 처리에 대한 메서드가 정의되어 있는 클래스
// char[] string = {'a', 'b', 'c', 'd'};
String string = " This is string contents ";
//.concat()은 +로 대체가능
//.substring(시작인덱스, 종료인덱스);
String subString = string.substring(6, 8);
System.out.println(subString); //is 출력
//.length();
//문자열 길이 가져오는 메서드
//.toUpperCase();
//모든 문자를 대문자로 교체
String upperCase = string.toUpperCase();
//.toLowerCase();
//모든 문자를 소문자로 교체
String lowerCase = string.toLowerCase();
System.out.println(upperCase);
System.out.println(lowerCase);
// THIS IS STRING CONTENTS
// this is string contents 각각 출력
//.indexOf(문자열);
//해당하는 문자열이 존재한다면 그 위치의 첫번째 인덱스 번호를 반환
//해당하는 문자열이 존재하지 않으면 -1 반환
int stringIndex = string.indexOf("is");
System.out.println(stringIndex); //3 출력
//존재하지 않는 문자를 검색하면 -1이 뜬다
//.trim();
//문자열의 앞뒤 공백 제서
String trimString = string.trim();
System.out.println(trimString);
//This is string contents 출력
//앞뒤 공백이 없어진다.
//.replaceAll(변환할 문자열, 변환될 문자열);
// 특정 문자열을 지정한 문자열로 변경
String replacsString = string.replaceAll("is", "are");
System.out.println(replacsString);
// Thare are string contents 출력
//3️⃣Wrapper class
//기본형 데이터 타입을 참조형 데이터 타입으로 다루기 위한 클래스
//💡왜 참조형으로 다루려고하지🤔
//참조형 클래스에 기본형 클래스 넣을수 없어서 사용한다?
//int -> Integer
//double -> Double
//...
Integer integer = 10;
int number = integer;
//문자열 -> 숫자
String numberString = "110";
number = Integer.parseInt(numberString);
System.out.println(number); //숫자110
//숫자 -> 문자열
numberString = Integer.toString(550);
System.out.println(numberString);//문자열550
//4️⃣Random class
// 무작위의 값을 얻고자 할때 유용한 클래스
Random random = new Random();
//.nextInt() : 무작위의 int형 정수
//.nextLong() : 무작위의 long형 정수
//.nextInt(최대값) : 최대값보다 작은 int형 정수 //양수만 나옴
int randomNumber = random.nextInt(3);
System.out.println(randomNumber);
//로또번호 생성기 만들기 : 중복된 값이 없어야한다.
//배열만 쓰게 되면 중복을 제거하거나 정렬할때도 로직을 짜줘야한다.
int[] lotto = new int[6];
//로또번호 6자리이므로 배열크기 6으로
for(int index = 0 ; index < lotto.length ; index++) {
//중복값제거
🟢boolean equal = false;
int lottoNumber = random.nextInt(45) + 1;
//0~44가 1~45가된다
for(int subIndex = 0 ; subIndex < index ; subIndex++) {
//lottoNumber안에는 1부터 45값이 들어가 있으므로
//index = 1, subIndex = 0인 경우 밑의 if문이 안돌아간다.
if(lotto[subIndex]==lottoNumber) {
//continue;
//맨처음에 continue; 적었었는데
//이렇게 되면 이 if문만 나가고
//for문으로 돌아가게된다. →중복값나온다?
// System.out.println(lotto[subIndex]
// + " " + lotto[index]);
equal = true;
}
🟢}
if(equal) {
--index;
continue;
}
// lotto[index] = random.nextInt(45) + 1;
//0~44가 1~45가된다
lotto[index] = lottoNumber;
}
for(int lottoNumber : lotto) {
System.out.print(lottoNumber + " ");
}
}
메서드에 전달된 매개변수를 수정하기 위해서는
기본형 타입의 변수를 참조형 변수로 변환해야한다.
기본형 변수는 값으로만 전달되기 때문이다.
출처 https://coding-factory.tistory.com/547
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;
// 날짜 및 시간
public class DateTime {
public static void main(String[] args) {
//System.currentTimeMillis()
//현재시간을 long타입으로 0.001초 단위로 표현
//기준 1970년 1월 1일 / 기준으로부터 얼마나 지났는지 표시
long startTime = System.currentTimeMillis();
System.out.println(startTime); //1678361843575 형식으로 출력
for(int count = 0 ; count < 1000000000; count++) {
count++;
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);//걸린 작업시간 출력
//Date class
//날짜를 관리해주는 클래스
//주로 날짜와 관련된 데이터타입을 취급할때 사용, 연산할때는 거의 쓰이지 않는다.
//데이트 타입의 데이트를 저장할때 사용한다
Date date = new Date();
System.out.println(date);//Thu Mar 09 20:37:23 KST 2023
System.out.println(date.getMonth());
//지금 3월인데 2로나옴 : index개념으로 다뤄서 그렇다
//값을 저장하는 용도로만 많이 사용한다
date.setHours(10);
// date.setHours(date.getHours() + 2); //로도 사용한다
System.out.println(date);
//Thu Mar 09 10:37:23 KST 2023 시간이 10시로 설정
//요즘에 많이 쓰이는 방법
Date now = Date.from(Instant.now());
//타임객체를 date로 바꾸는 과정
System.out.println(now); //Thu Mar 09 20:37:23 KST 2023
//시간 추가 또는 바꾸려면 이 방식을 외워야한다..
Date minusTwoHour = date.from(Instant.now().minus(2, ChronoUnit.HOURS));
System.out.println(minusTwoHour); //Thu Mar 09 18:37:23 KST 2023
//2시간 빠진 값이 출력된다
//SimpleDateFormat
// Date타입의 참조변수를 지정한 포멧의 문자열로 변경해주는 클래스
//y : 연, M : 월, d : 일, H : 시간, : m 분, s : 초
SimpleDateFormat simpleDateFormat/*sdf로 적는 사람도 있음*/ =
new SimpleDateFormat("yyyy. MM. dd. HH:mm:ss");
String formatedDate = simpleDateFormat.format(now);
System.out.println(formatedDate); //2023. 03. 09. 20:37:23
//Time Package
//Date와 Calander class의 단점 보완
//LocalDate class
//날짜를 관리해주는 class
LocalDate localDate = LocalDate.now();
System.out.println(localDate); //2023-03-09
//특정 날짜를 지정하는 of()
🟣LocalDate localDateOf = LocalDate.of(2022, 12, 25);
System.out.println(localDateOf); //2022-12-25
//LocalTime class
//시간을 관리해주는 class
LocalTime localTime = LocalTime.now();
System.out.println(localTime); //20:37:23.628216
//특정 시간을 지정하는 of()
🟣LocalTime localTimeOf = LocalTime.of(12, 40);
System.out.println(localTimeOf); //12:40
//LocalDateTime class
//날짜와 시간을 관리해주는 class
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime); //2023-03-09T20:37:23.628216
//특정 날짜와 시간을 지정하는 of()
LocalDateTime localDateTimeOf =
LocalDateTime.of(localDateOf, localTimeOf); //🟣 받아옴
System.out.println(localDateTimeOf); //2022-12-25T12:40
//백엔드는 날짜를 다루지 않는다.
//대부분 프론트엔드에서 선택한 날짜 받아오거나 현재날짜 등록하는것 정도.
}
}
정확한 소수점 연산을 해야할때 사용
import java.math.BigDecimal;
double a = 34.96753;
double b = 45.65431;
System.out.println(a + b); //80.62183999999999
BigDecimal number = new BigDecimal(String.valueOf(a));
BigDecimal number2 = new BigDecimal(String.valueOf(b));
System.out.println(number.add(number2)); //80.62184