JAVA/자바 실습 / / 2021. 4. 12. 23:57

Java | Lab4_Ex

01. ArithmeticException 예외 프로그램

º 두 정수를 입력 받아 나눗셈을 하고 몫을 구하는 프로그램

- 사용자가 나누는 수에 0을 입력하면 ArithmeticException 예외가 발생하여 프로그램이 강제 종료된다.

import java.util.Scanner;
public class DivideByZero {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int dividend, divisor;   //나뉨수와 나눔수 선언
		System.out.println("나뉨수 입력: ");
		dividend = s.nextInt();
		System.out.println("나눔수 입력: ");
		divisor = s.nextInt();
		
		System.out.println(dividend + "를 " + divisor + "로 나누면 몫은 " + dividend/divisor + "입니다.");
		
		s.close();
	}
}

02. ArithmeticException 예외처리 프로그램

º try-catch 블록을 이용하여, 정수를 0으로 나누는 경우에 "0으로 나눌 수 없습니다!"를 출력하고 다시 입력 받는 프로그램

import java.util.Scanner;
public class DivideByZero {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int dividend, divisor;   //나뉨수와 나눔수 선언
		System.out.println("나뉨수 입력: ");
		dividend = s.nextInt();
		System.out.println("나눔수 입력: ");
		divisor = s.nextInt();
		
		try {
		System.out.println(dividend + "를 " + divisor + "로 나누면 몫은 " + dividend/divisor + "입니다.");
		}catch(ArithmeticException e) {
			System.out.println("0으로 나눌 수 없습니다!");
		}
		s.close();
	}
}


03. ArrayIndexOutOfBoundsException 예외처리

º 배열의 인덱스가 범위를 벗어날 때 발생하는 ArrayIndexOutOfBoundsException을 처리하는 프로그램

public class ArrayEx {
	public static void main(String[] args) {
		int[] intArray = new int[5];
		intArray[0] = 0;
		try {
			for(int i=0; i<5; i++) {
				intArray[i+1] = i+1+intArray[i];
				System.out.println("intArray["+i+"]"+"="+intArray[i]);
			}
			
		}catch(ArrayIndexOutOfBoundsException e) {
			System.out.println("배열의 인덱스가 범위를 벗어났습니다!");
		}
	}
}


04. InputMismatchException 예외처리 프로그램

º 3개의 정수를 입력받아 합을 구하는 프로그램

- 사용자가 정수가 아닌 문자를 입력할 때 발생하는 InputMismatchException 예외를 처리하여 다시 입력받도록 처리

import java.util.Scanner;
import java.util.InputMismatchException;
public class InputEx {
	public static void main(String[] args) {
		Scanner a = new Scanner(System.in);
		int sum = 0, n = 0;
		for(int i=0; i<3; i++) {
			System.out.println(i + " >> ");
			try {
				n = a.nextInt();
			}catch(InputMismatchException e) {
				System.out.println("정수가 아닙니다!");
				a.next();
				i--;
				continue;
			}
			sum += n;
		}
		System.out.println("합은 " + sum);
		a.close();
	}
}


05. NumberFormatException 예외처리 프로그램
º 정수가 아닌 문자열을 정수로 변환할 때 발생하는 NumberFormatException을 처리하는 프로그램

public class NumEx {
	public static void main(String[] args) {
		String[] stringNumber = {"23", "12", "998", "3.141592"};
		int i = 0;
		try {
			for(i=0; i<stringNumber.length; i++) {
				int j = Integer.parseInt(stringNumber[i]);
				System.out.println("정수로 변환된 값은 " + j );
			}
		}
		catch(NumberFormatException e) {
			System.out.println("정수로 변환할 수 없습니다!");
		}
	}
}


06. 예외처리를 한번에 처리하는 프로그램

public class Exception01 {
	public static void main(String[] args) {
		int [] abc = new int[3];
		try {
			abc[2] = 10/0;
			abc[3] = 1000;
		}catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("배열의 인덱스가 범위를 벗어났어요!");
		}catch (ArithmeticException e) {
			System.out.println("0으로 나눌 수 없습니다!");
		} finally {
			System.out.println("무조건 실행합니다!");
		}
	}
}


07. 오류 메시지 출력 프로그램

public class ExMessage {
	public static void main(String[] args) {
		int a = 10, b = 0;
		int result;
		try {
			result = a/b;
		}catch (ArithmeticException e) {
			System.out.print("오류메시지: ");
			System.out.println(e.getMessage());  //e변수에서 메시지를 추출해서 출력
		}
	}
}


08. 사용자 지정 오류 메시지 출력 프로그램

public class ExMessage01 {
	public static void main(String[] args) {
		int a = 1000, b = 0;
		int result;
		try {
			if(b==0)
				throw new Exception("0으로 나눌 수 없습니다!");
			result = a/b;
		}catch (Exception e) {                  //예외 타입을 exception으로 변경
			System.out.print("오류 메시지: ");  
			System.out.println(e.getMessage()); //e변수에서 메시지를 추출해서 출력
		}
	}
}

 

'JAVA > 자바 실습' 카테고리의 다른 글

Java | Lab6  (0) 2021.04.16
Java | Lab5  (0) 2021.04.15
Java | Lab4  (0) 2021.04.12
Java | Lab3  (0) 2021.04.12
Java | Lab2  (0) 2021.04.11
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유