Day 35 (23.02.14)

Jane·2023년 2월 14일
0

IT 수업 정리

목록 보기
39/124

1. throws 예외처리

1-1. throws의 사용법

import java.util.InputMismatchException;
import java.util.Scanner;

class JavaPractice {

	public static void main(String[] args) throws InputMismatchException {
		Scanner sc = new Scanner(System.in);
		
		int num = sc.nextInt();
		// int가 아닌 다른 것을 넣으면 Exception 처리
		
		System.out.println(num);

	}
}

  • 함수 옆에 throws (Exception 종류)를 추가한다.
  • 에러가 발생할 경우 Call Stack을 보여주고 정지한다.
  • 두 개 이상의 함수 종류는 반점(,)으로 이어붙여서 같이 쓸 수 있다.
    (throws IOException, InputMismatchException)
  • throw Exception으로 다형성을 적용하여 쓸 수 있다.

1-2. throws + try~catch

import java.util.InputMismatchException;
import java.util.Scanner;

class JavaPractice {

	public static void function1() throws InputMismatchException {
		Scanner sc = new Scanner(System.in);
		int num = sc.nextInt();
		System.out.println("function1");
	}

	public static void main(String[] args) {

		try {
			function1();
		} catch (Exception e) {
			System.out.println("Exception Catch");
		}
	}
}

[Console]
(입력) dsaf
Exception Catch

2. Error와 Exception의 관계

  • Throwable이 Object를 상속한다
  • Exception과 Error가 Throwable을 상속한다
  • Error의 종류
    • OutOfMemory Error
    • VirtualMachine Error
    • StackOverflow Error
  • Exception의 종류
    • Unchecked Exception (실시간 오류)
      Arithmetic Exception, NullPointer Exception, ClassCast Exception, IndexOutOfBoundsException, InputMismatch Exception
    • Checked Exception (반드시 예외 처리를 할 것!)
      IO Exception (input-output), SQL Exception, ClassNotFound Exception

3. 예외처리 예제

3-1. 예외처리가 필요한 상황

import java.io.BufferedWriter;
import java.util.Scanner;

class JavaPractice {
	public static void function1() {
		BufferedWriter writer = null;
		writer.write('A');
	}
	
	public static void main(String[] args) throws Exception {
		function1();
	}
}

  • 무언가를 쓰려는(input) 상황에서, 예외처리를 하지 않아서 생겼다.

  • write()는 IO Exception을 throw 하고 있다.
    IO Exception은 Checked Exception이므로, 반드시 예외처리를 하도록 한다.

3-2. 해결법

  • 함수 안에 예외 처리 내용을 넣으면 된다!

방법 1. try ~ catch를 이용하기

public static void function1() {
	BufferedWriter writer = null;
	try {
		writer.write('A');
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

방법 2. throws 이용하기

public static void function1() throws IOException {
	BufferedWriter writer = null;
	writer.write('A');
}

4. JVM과 메모리 관리

  • JVM이 메모리 관리를 해준다.
  • 주요 영역 : Method Area / Call Stack / Heap
  • 참조하지 않는 것(null) : Garbage Collector에 보관 후 정리
profile
velog, GitHub, Notion 등에 작업물을 정리하고 있습니다.

0개의 댓글