Hi

Exception(예외)와 try-with-resources 본문

Programming/Java

Exception(예외)와 try-with-resources

SharingWorld 2018. 3. 29. 14:51

 Exception


 * Checked Exception:
 => 반드시 사용자가 예외 처리를 하던가, 외부로 던져야 한다.
 => IOException


 * Unchecked Exception:
 => 처리하지 않아도 되지만, 예외 발생시 프로그램이 종료된다.


스택을 만들어보자
import java.io.*;

class User {
	private String name;
	private int age;

	public User(String name, int age) {
		this.name = name;
		this.age = age;
	}

// Java 7: Try with Resource
// C#: using 구문
	public void save(String filename) {
		try (FileOutputStream fos = new FileOutputStream(filename);
			DataOutputStream dos = new DataOutputStream(fos)) {

			dos.writeInt(age);
			dos.writeBytes(name);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

/* Java 6
// FileOutputStream
public void save(String filename) {
	FileOutputStream fos = null;
	DataOutputStream dos = null;

	try {
		fos = new FileOutputStream(filename);
		dos = new DataOutputStream(fos);

		dos.writeInt(age);
		dos.writeBytes(name);

	} catch (IOException e) {
		e.printStackTrace();

	} finally {
		try {
			if (fos != null)
				fos.close();
		} catch (IOException e) {

		}

		try {
			if (dos != null)
				dos.close();
		} catch (IOException e) {

		}

	}
}
*/

@Override
public String toString() {
	return "User{" +
	"name='" + name + '\'' +
	", age=" + age +
	'}';
}
}


public class Program_0322 {

}