Programming/JAVA

JAVA 6

우드의개발개발 2023. 2. 20. 17:32

 ✅ 이것만은 꼭 정리해놓자! 

try {
    // code to be monitored for exceptions goes here
} catch (IOException e) {
    System.err.println("An IO error occurred: " + e.getMessage());
} catch (Exception e) {
    System.err.println("An error occurred: " + e.getMessage());
    e.printStackTrace();
} finally {
    // code to be executed regardless of whether an exception occurred or not goes here
}
ArithmeticException
This exception is thrown when an arithmetic operation results in an overflow, underflow, or 
division by zero.

NullPointerException - This exception is thrown when you try to access an object or variable 
that is null.

ArrayIndexOutOfBoundsException - This exception is thrown when you try to access an array 
element with an invalid index.

ClassCastException - This exception is thrown when you try to cast an object to a type that is 
not compatible with its actual type.

NumberFormatException - This exception is thrown when you try to convert a string to a numeric 
value, but the string does not represent a valid number.

IOException - This exception is thrown when an I/O error occurs, such as when reading or 
writing a file.

SQLException - This exception is thrown when an error occurs while working with a database.

InterruptedException - This exception is thrown when a thread is interrupted while it is 
waiting, sleeping, or performing some other blocking operation.

RuntimeException - This is a general-purpose exception that can be thrown for a wide variety 
of runtime errors.

try 는 필수 구문이고 catch는 선택이다. 하지만 catch를 써야지만 에러가 발생했을 때 이를 핸들링 할 수 있다. java의 대표적인 error에는 아래와 같은 에러가 있다. finally 구문은 에러와 상관 없이 기본적으로 실행되는 부문이다.

 

 ✅ 이것만은 꼭 정리해놓자! 

Exception 만들기

 

new Exception()

public class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

public class example {
    public void doSomething() throws CustomException {
        if (true) {
            throw new CustomException("Something went wrong.");
        }
    }
}

 

new RunTimeException()

public class test {
  public void doSomething() {
    // some code that may throw CustomException
    if (true) {
      throw new RuntimeException("Something went wrong.");
    }
  }
}

 

 

throw 문법

public class Main {

  public static void main(String[] args) {
    try {
      int result = divide(10, 0);
      System.out.println("Result: " + result);
    } catch (RuntimeException e) {
      System.out.println("Caught a RuntimeException: " + e.getMessage());
    }

  }

  public static int divide(int dividend, int divisor) {
    if (divisor == 0) {
      throw new RuntimeException("Divisor cannot be zero.");
    }
    return dividend / divisor;
  }
}

 

 📖 연습 문제) equals(), hashCode() 

public class Money {

  private int value;

  public Money(int value) {
    this.value = value;
  }

  private int getValue(Money money) {
    return money.value;
  }

  @Override
  public boolean equals(Object o) {
    if (getClass() != o.getClass()) {
      return false;
    }
    Money m = (Money) (o);
    if (this.value == m.getValue(m)) {
      return true;
    }
    return false;
  }
}

 

 🎯 문자 말고 숫자만 입력하라구! 

package OnlyNumber;

import java.util.Scanner;

public class Main {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    boolean isContinued = true;
    while (isContinued) {
      System.out.println("숫자를 입력해주세요.");
      String input = scanner.nextLine();
      int number;
      try {
        number = Integer.parseInt(input);
        System.out.println("입력하신 숫자는 " + number + "입니다.");
      } catch (NumberFormatException e) {
        System.out.println("잘못된 값을 입력하셨습니다.");
      }
    }
  }
}

 

 🎯 휴대폰 번호 입력받기 v1 

package ex6.PhoneNumberV1;

interface TypeCheck {

  public void checkIsAllDigits(String phoneNumber);

  public void checkFirstThreeDigits(String phoneNumber);

  public void checkTotalLength(String phoneNumber);
}
package ex6.PhoneNumberV1;

import java.util.Scanner;

public class Input {

  Scanner sc = new Scanner(System.in);

  String inputPhoneNumber() {
    System.out.println("휴대폰 번호를 입력해주세요.");
    String phoneNumber = sc.nextLine();
    return phoneNumber;
  }
}
package ex6.PhoneNumberV1;

public class PhoneNumber implements TypeCheck {

  private String value;

  public PhoneNumber() {
    Input input = new Input();
    String phoneNumber = input.inputPhoneNumber();
    this.validate(phoneNumber);
    this.value = phoneNumber;
  }

  private void validate(String phoneNumber) {
    checkIsAllDigits(phoneNumber);
    checkFirstThreeDigits(phoneNumber);
    checkTotalLength(phoneNumber);
    getPhoneNumberFormally(phoneNumber);
  }

  @Override
  public void checkIsAllDigits(String phoneNumber) {
    for (int i = 0; i < phoneNumber.length(); i++) {
      try {
        Integer.parseInt(String.valueOf(phoneNumber.charAt(i)));
      } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException("숫자를 입력해주세요.");
      }
    }
  }

  @Override
  public void checkFirstThreeDigits(String phoneNumber) {
    if (!phoneNumber.startsWith("010")) {
      throw new IllegalArgumentException("휴대폰 번호는 010으로 시작해야 합니다.");
    }
  }

  @Override
  public void checkTotalLength(String phoneNumber) {
    int totalLength = 0;
    for (int i = 0; i < phoneNumber.length(); i++) {
      totalLength += 1;
    }
    if (totalLength != 11) {
      throw new IllegalArgumentException("휴대폰 번호는 11글자여야 합니다.");
    }
  }

  private void getPhoneNumberFormally(String phoneNumber) {
    String res = "";
    for (int i = 0; i < phoneNumber.length(); i++) {
      if (i == 3 || i == 7) {
        res += "-";
      }
      res += phoneNumber.charAt(i);
    }
    System.out.println("휴대폰 번호를 정상적으로 입력하셨습니다. 입력하신 휴대폰 번호는 " + res + "입니다.");
  }
}
package ex6.PhoneNumberV1;

public class Main {

  public static void main(String[] args) {
    new PhoneNumber();
  }
}

 

 🎯 휴대폰 번호 입력받기 v2 

package ex6.PhoneNumberV2;

import java.util.Scanner;

public class PhoneNumber {

  private String value;

  public PhoneNumber() {
    this.value = this.checkFormat();
  }

  private String getPhoneNumberFormally(String ValidPhoneNumber) {
    String res = "";
    for (int i = 0; i < ValidPhoneNumber.length(); i++) {
      if (i == 3 || i == 7) {
        res += "-";
      }
      res += ValidPhoneNumber.charAt(i);
    }
    return res;
  }

  String checkFormat() {
    System.out.println("휴대폰 번호를 입력해주세요.");
    Scanner sc = new Scanner(System.in);
    String phoneNumber = sc.nextLine();

    // 입력 받은 문자열이 모두 숫자인지 확인
    for (int i = 0; i < phoneNumber.length(); i++) {
      try {
        char num = phoneNumber.charAt(i);
        Integer.parseInt(String.valueOf(num));
      } catch (NumberFormatException e) {
        System.out.println("숫자만 입력해주세요.");
        return checkFormat();
      }
    }

    // 핸드폰 번호 자릿수 확인
    if (phoneNumber.length() != 11) {
      System.out.println(phoneNumber.length());
      System.out.println("휴대폰 번호는 11글자여야 합니다.");
      return checkFormat();
    }

    // 입력 받은 문자열의 앞부분이 010인지 확인
    if (!phoneNumber.startsWith("010")) {
      System.out.println("휴대폰 앞자리는 010 이어야 합니다.");
      return checkFormat();
    }
    System.out.println(
        "휴대폰 번호를 정상적으로 입력하셨습니다. 입력하신 휴대폰 번호는 " + getPhoneNumberFormally(phoneNumber) + "입니다.");
    return phoneNumber;
  }
}
package ex6.PhoneNumberV2;

public class Main {

  public static void main(String[] args) throws Exception {
    new PhoneNumber();
  }
}

'Programming > JAVA' 카테고리의 다른 글

JAVA 5  (2) 2023.02.16
JAVA 4  (2) 2023.02.12
JAVA 3  (1) 2023.02.09
JAVA 2  (4) 2023.02.01
JAVA 1  (2) 2023.01.30