public class Main {
public static void main(String[] args) {
// 예외 처리 (Exception Handling)
// 1. try catch문
// 2. throw문
// 패턴
// try {
// 예외가 발생할만한 실행문
// } catch (예외클래스 객체) {
// 예외 발생 시 처리하는 실행문 - 오류 내용 출력
// }
String name = null;
System.out.println(name);
try {
// java.lang.NullPointerException
System.out.println(name.toLowerCase());
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace(); // System.err 출력(가장 마지막에 출력됨)
} finally {
System.out.println("예외 처리 구문");
}
try {
int[] nums = {10,20,30};
//System.out.println( nums[3] );
//System.out.println( 10 / 0 );
String str = null;
//str.toLowerCase();
}
catch (ArrayIndexOutOfBoundsException e){
System.out.println("인덱스 예외발생!");
e.printStackTrace();
}
catch (ArithmeticException e){
System.out.println("산술 예외발생!");
e.printStackTrace();
}
catch (Exception e){
System.out.println("그외의 예외발생!");
e.printStackTrace();
}
finally {
//예외가 발생하든 안하든 무조건 호출되는 블럭
// 마무리 정리하는 코드
System.out.println("정리하는 코드");
}
}
}
throws: 메서드 선언 시 사용하며 예외 처리를 해당 메서드 내에서가 이난 해당 메서드를 호출해서 사용하는 쪽에서 처리해야 함.throw: 강제 오류 발생public class Main {
public static void main(String[] args) {
//throws 문
// : 자신을 호출한 메소드에 예외처리를 떠넘기는 것.
try {
myFunc();
}
catch (Exception e){
MyException e2 = (MyException)e;
e2.printMessage();
}
}
static void myFunc() throws Exception{
MyException e = new MyException();
e.message = "사용자 정의 예외";
throw e;
//
// System.out.println( 10 / 0 ); //산술 오류!
// System.out.println(" ---- ");
}
}
//사용자 정의 예외
class MyException extends Exception {
String message = "";
public void printMessage(){
System.out.println(this.message);
}
}
close()를 실행하지 않아도 됨.import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try(FileWriter file = new FileWriter("data.txt")) {
file.write("안녕하세요~");
}
catch (IOException e){
e.printStackTrace();
}
try(FileReader file = new FileReader("data.txt")) {
int data = 0;
do {
data = file.read();
if( data != -1 ){ // -1 = EOF(End Of File)
System.out.print((char)data);
}
}
while ( data != -1 ); // End Of File
}
catch (IOException e){
e.printStackTrace();
}
}
}
catch 블록에서 처리import java.io.*;
public class CloseExceptionExample {
public static void main(String[] args) {
try (FileReader reader = new FileReader("input.txt");
FileWriter writer = new FileWriter("output.txt")) {
// 파일 읽기 및 쓰기 작업
int data;
while ((data = reader.read()) != -1) {
writer.write(data);
}
} catch (IOException e) {
System.out.println("예외 발생: " + e.getMessage());
}
// 두 자원에 대한 close() 호출 시 예외가 발생할 수 있음
}
}
Run으로 두 파일을 실행해도 되고 terminal에서 javac로 컴파일 후 java [file name]으로 실행해도 됨javac server.java
java server
javac client.java
java client
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
//인터넷 통신
//1. TCP/IP(Socket통신) : 게임,채팅에 사용됨.
// : 속도가 빠르다.
// : 연결지향(한번 접속하면, 계속 연결이 지속됨.)
// : 비공개 포트방식(Port : 컴퓨터에서 응용프로그램마다 가지는 통신창구)
// : 공식포트 80 HTTP, 21 FTP, 443 HTTPS
//2. HTTP통신 : 대부분의 웹앱에서 사용됨.
// : 공식포트 80이나 443포트만 이용, 내부망에서 8080,8090포트들이 사용됨.
// : 웹브라우저 서버스 대응 용도에 사용됨.
//클라이언트(서비스를 제공받으면 클라) <--> 서버(서비스를 제공하면 서버)
public class ex48_client {
public static void main(String[] args) {
Socket socket = null;
socket = new Socket();
try {
socket.connect(
//127.0.0.1 : 접속하려는 컴퓨터의 주소를 말함. localhost와 같은 말.
new InetSocketAddress("localhost", 5001)
);
System.out.println("서버 접속 성공!");
//서버에 문자열형으로 데이타를 보내보자.
byte[] bytes = null;
String message = null;
OutputStream os = socket.getOutputStream();
message = "Hi! This is Client~";
//UTF-8 : 문자인코딩(부호화,암호화) 타입
//문자인코딩타입 : ASCII(영문), EUC-KR(완성형한글), UTF-8(유니코드-전세계문자)
// : cp949(ms949) 윈도우즈 한글 인코딩
bytes = message.getBytes("UTF-8");
os.write(bytes);
os.flush(); //버퍼에 데이타를 다 내보낸다.
System.out.println("데이타보내기 성공!");
//서버로부터 데이터 받기
InputStream is = socket.getInputStream();
bytes = new byte[1024];
int readByteCount = is.read(bytes);
message = new String(bytes, 0, readByteCount, "UTF-8");
System.out.println("데이타받기 성공:"+message);
os.close();
is.close();
} catch (Exception e) {
System.out.println("서버 접속 오류!");
}
}
}
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
//테스트 방법
//1. 서버 소켓을 먼저 실행함.
//2. 클라 소켓을 나중에 실행함.
public class ex49_server {
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket();
serverSocket.bind(
//127.0.0.1 : 접속하려는 컴퓨터의 주소를 말함. localhost와 같은 말.
new InetSocketAddress("127.0.0.1", 5001) );
while( true ){
System.out.println("서버가 연결을 기다리는 중...");
Socket socket = serverSocket.accept(); //Blocking..대기중..
InetSocketAddress isa =
(InetSocketAddress)socket.getRemoteSocketAddress();
System.out.println("서버가 연결을 수락함:"+isa.getHostName());
//클라이언트 데이타를 수신한다.
byte[] bytes = null;
String message = null;
InputStream is = socket.getInputStream();
bytes = new byte[1024]; //1024바이트만큼 버퍼메모리 생성
int readByteCount = is.read(bytes);
message = new String(bytes, 0, readByteCount, "UTF-8");
System.out.println("서버가 데이타받기 성공함.");
System.out.println("서버가 받은 데이타:"+message);
//서버에서 클라로 데이타 보내기
OutputStream os = socket.getOutputStream();
message = "Hi~ This is Server~";
bytes = message.getBytes("UTF-8");
os.write(bytes);
os.flush(); //버퍼에 있는 데이타 밀어내기
System.out.println("서버가 클라에게 데이타보내기 성공");
is.close();
os.close();
socket.close();
if(message.equals("exit")){ //"exit"문자열이면 서버 종료!
break;
}
}
} catch (Exception e) {
System.out.println("서버 초기화 에러!");
}
}
}
출처: 한국경제신문 K-Digital Training - toss bank
첨고 서적:
최원효 지음, 입문자의 눈높이에 맞춰 문법과 개념을 설명하는 자바 입문서 코딩 자율학습 자바 입문, 길벗, 2024년