/ W3SCHOOLS

W3schools - Exception

이 페이지는 다음에 대한 공부 기록입니다
Lecture에서 배웠던 내용을 복습하며 작성했습니다

찾으시는 정보가 있으시다면
주제별reference를 이용하시거나
우측 상단에 있는 검색기능을 이용해주세요

Exception – try catch

When an error occurs, Java will normally stop and generate an error message

The techinal term for this is : Java will throw an exception

try and catch

try statement

  • allows you to define a code block to be tested for errors while is being executed

catch statement

  • allows you to define a code block to be executed, if an error occurs in the try block

try and catch keywords come in pairs

finally statement

  • lets you execute code, after try-catch, regardless of the result
public class Main {
	public static void main(String[] args){
		try {
			int[] myNumbers = {1,2,3};
			System.out.println(myNumbers[10]);
		} catch (Exception e) {
			System.out.println(Something went wrong.);
		} finally {
			System.out.println(The \‘try catch\’ is finished.);
		}
	}
}

The output will be

Something went wrong.
The ‘try catch’ is finished.

throw

Allows you to create a custom error

Is used together with an exception type

public class Main {
	static void checkAge(int age) {
		if (age < 18) {
			throw new ArithmeticException(Access denied  You must be at least 18 years old.);
		}else{
			System.out.println(Access granted  You are old enough!);
		}
	}

if you call checkAge(15); in main method, the output will be

Exception in thread “main” java.lang.ArithmeticException : Access denied – You must be at least 18 years old.