코딩은 실력보다 시력이지

빅데이터교육과정/JAVA

DAY 12. 예외처리와 스레드

Listeria 2021. 2. 23. 02:42
import static java.lang.System.out;

class ExceptEx {

	public static void main(String[] args) {
		
		int[] var = {10,20,30};
		
		for(int i =0; i<=3;i++)
			try {
				out.printf("var[%d] : %d\n",i,var[i]);
			}catch(ArrayIndexOutOfBoundsException ae) {
				out.println("out");
			}
		out.println("end");
	}
}

 

import java.util.InputMismatchException;
import java.util.Scanner;
import static java.lang.System.out;
public class ExceptEx2 {

	public static void main(String[] args) {
		
		int var = 50;
		
		try {
			System.out.println("Input Integer : ");
			int data = new Scanner(System.in).nextInt();
			out.println(var/data);
		}catch(NumberFormatException ne) {
			out.println("not num1");
		}catch(ArithmeticException ae) {
			out.println("0? kidding me?");
		}catch(Exception ie) {
			out.println("not num2");	
		}
		out.println("end");
	}

}
import static java.lang.System.out;


public class ThrowEx1 {

	public void setData(String n) throws NumberFormatException{
		if (n.length()>=1) {
			String str = n.substring(0,1);
			printData(str);
		}
	}
	
	public void printData(String n) throws NumberFormatException{
		int dan = Integer.parseInt(n);
		out.print(dan+"단\n");
		out.print("--------------------------\n");
		
		for(int i=0;i<9;i++) {
			out.printf("%d * %d = %d\n",dan,(i+1),dan*(i+1));
		}
		
	}
	
	
	public static void main(String[] args) {
	
		ThrowEx1 t1 = new ThrowEx1();
		try {
			t1.setData(args[0]);
		}catch(Exception e) {
			out.printf("1st input isn't num\n");
		}
		
	}

}

 

일반적으론 코드가 순차적으로 실행되다가 오류가 발생하면 그 즉시 멈추게 된다. 하지만 오류가 발생했을때 멈추지 않고 계속 진행을 시키고 싶을때 Try-catch 혹은 throws를 이용할 수 있다. Try-catch문의 경우 일반적으로는 Try 내부의 프로그램을 실행하지만 예외처리(catch)한 오류가 발생했을 경우 catch문을 실행한다. Throws의 경우에는 사전에 설정해둔 예외 처리를 실행한다.throws와 유사하게 생긴 throw가 있는데 이는 개발자가 임의로 에러를 발생시키고자 할 때 사용한다.

 

import static java.lang.System.out;

public class FinallyEx1 {

	public static void main(String[] args) {
		
		int[] var = {10,20,30};
		
		for(int i =0; i<=3;i++)
			try {
				out.printf("var[%d] : %d\n",i,var[i]);
			}catch(ArrayIndexOutOfBoundsException ae) {
				out.println("out");
				return;
			}finally {
				out.println("찐막");
			}
		out.println("end");
	}
}

 

 

코드가 실행되다가 예기치 못한 오류로 인해 멈추거나 종료되더라도 반드시 수행해야 하는 코드를 finally에 작성해두면 종료되기 직전 finally 내부의 코드는 실행을 한 뒤 종료되게 된다.


class ATMM extends Thread{
	private long depositeMoney = 10000;
	public void run() {
		synchronized(this) {
			for (int i=0; i<10;i++) {
				try {
					notify();
					Thread.sleep(1000);
					wait();					
				}catch(InterruptedException e) {
					e.printStackTrace();
				}
				if (getDepositeMoney()<=0)
					break;
				withDraw(1000);
			}
		}
	}

	public void withDraw(long howMuch) {
		if(getDepositeMoney()>0) {
			depositeMoney -=howMuch;
			System.out.print(Thread.currentThread().getName()+" : ");
			System.out.printf("잔액 : %,d 원 %n",getDepositeMoney());
		}else {
			System.out.println(Thread.currentThread().getName());
			System.out.println("empty");
		}
	}

	public long getDepositeMoney() {
		return depositeMoney;
	}
}



public class ATM{

	public static void main(String[] args) {
		
		ATMM atm = new ATMM();
		Thread mother = new Thread(atm,"mother");
		Thread son = new Thread(atm,"son");
		mother.start();

		son.start();
		
	}

}

 

thread는 프로그램이 실행 되는 중에도 wait 을 통해 다른 thread의 작동을 체크하고 인터럽트가 발생했다면 해당 내용을 실행하거나 변경사항을 동기화 시켜 작동중인 프로그램에 변화를 반영시킬 수 있다.