728x90

예외 처리

오류

컴파일 오류 

컴파일러가 코드를 컴파일하지 못하는 문제로, 보통 프로그램 소스 코드의 문법이 잘못되었을 때 나타난다. 

런타임 오류

프로그램을 실행하는 과정에서 발생하는 오류이다. 


예외

파일 입출력을 할 때 파일 또는 디렉터리 이름을 잘못 기재했거나 없을 때

네트워크 프로그램에서 접속할 서버의 주소가 틀렸거나 서버가 다운되었을 때

키보드에서 값을 입력받아야 하는데, 키보드를 연결하지 않았을 때

배열의 크기를 초과해서 배열 원소에 접근할 때

초기화하지 않은 객체를 사용할 때

데이터베이스 프로그램에서 데이터베이스의 주소, 아이디, 비밀번호, 스키마, SQL 쿼리 등이 잘못되었을 때 


try {

예외 처리를 요구하는 메서드 호출 부분

} catch (XXException e) {

예외 처리 코드 블록

} finally {

예외 상황이나 그렇지 않을 때 모두 처리되는 블록

}


e.printStackTrace()


1
2
3
4
5
6
7
8
9
10
import java.io.FileInputStream;
 
public class ExceptionTest {
    public static void main(String[] args) {
        FileInputStream fis;
        fis = new FileInputStream("/tmp/a.txt");
        System.out.println(fis.read());
    }
}
 
cs


-> 예외 발생 -> alt + Enter -> try catch


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
 
public class ExceptionTest {
    public static void main(String[] args) {
        FileInputStream fis;
        try {
            fis = new FileInputStream("/tmp/a.txt");
            System.out.println(fis.read());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
cs


throws는 예외처리를 한 번 미루는 것

원칙적으로는 main에는 달면 안됨

예외처리를 한 번 미루면 main에서 부를 때 try catch해줘야함


throw는 강제로 예외 발생


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class MyException extends Exception {
    private String message = null;
    public MyException() {
        super();
        message = "커스텀 예외 발생!";
    }
    @Override
    public String toString() {
        return message;
    }
}
 
public class ExceptionTest {
    public void print() throws MyException {
        System.out.println("메세지 출력");
        throw new MyException();
    }
    public static void main(String[] args) {
        ExceptionTest et = new ExceptionTest();
        try {
            et.print();
        } catch (MyException e) {
            e.printStackTrace();
        }
    }
}
 
cs


스레드

1)

Thread 클래스

2)

Runnable 인터페이스 구현


1
2
3
4
5
6
7
8
9
10
11
12
13
14
class MyThread extends Thread {
    @Override
    public void run() {
        // 새 스레드의 main메소드
        System.out.println("Thread()");
    }
}
public class Main {
    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        thread1.start();
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class MyThread extends Thread {
    @Override
    public void run() {
        // 새 스레드의 main메소드
        System.out.println();
    }
}
public class Main {
    public static void main(String[] args) {
        String name = Thread.currentThread().getName();
        System.out.println(name);
        MyThread thread1 = new MyThread();
        thread1.start();
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class MyThread extends Thread {
    @Override
    public void run() {
        // 새 스레드의 main메소드
        System.out.println("스레드 이름 : "+Thread.currentThread().getName());
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println("스레드 이름 : "+Thread.currentThread().getName());
        MyThread thread1 = new MyThread();
        thread1.start();
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class MyThread1 extends Thread {
    @Override
    public void run() {
        for(int i=1;i<=100;i++)
            System.out.print(i);
    }
}
class MyThread2 implements Runnable {
    public MyThread2() {
        System.out.println("Thread2");
    }
    @Override
    public void run() {
        System.out.println();
        for(char c='A';c<='Z';c++)
            System.out.print(c);
    }
}
public class Main {
    public static void main(String[] args) {
        MyThread1 thread1 = new MyThread1();
        thread1.start();
//        MyThread2 my2 = new MyThread2();
//        Thread thread2 = new Thread(my2);
        try {
            thread1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        thread2.start();
//        my2.run(); // 현재 스레드에서 run() 메소드 호출
 
        new Thread(new Runnable() {
            @Override
            public void run() {
                MyThread2 my2 = new MyThread2();
                my2.run();
            }
        }).start();
 
    }
}
 
cs


멀티 스레드

Thread.sleep()


멀티 스레드 동기화 문제 해결법

1) 해제 후 점유

2) 특정 리소스만 점유


synchronized


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class Main extends Thread{
    public int total;
    private SellManager sm;
 
    @Override
    public void run() {
        String tname = Thread.currentThread().getName();
        for(int i=0;i<3;i++){
            System.out.println(tname + "-판매:"+sm.sell());
        }
        System.out.println(tname + "종료");
    }
    public Main() {
        sm = new SellManager();
        total = 100;
    }
 
    public static void main(String[] args) {
        System.out.println("## 티켓 예매 프로그램 ##");
        Main app = new Main();
        for(int i=0;i<10;i++){
            Thread mt = new Thread(app);
            mt.start();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Main Thread 종료");
    }
 
    class SellManager {
        synchronized int sell() {
            total --;
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return total;
        }
    }
}
 
cs


람다식


람다식은 자바 8의 가장 큰 특징 중 하나로, 함수형 프로그래밍의 기본이 된다.

함수에 기반을 두고 데이터를 중심으로 프로그램을 기술하는 형태인 함수형 언어에는 LISP, 하스켈(Haskell), 얼랭(Erlang), F#, 클로저(Clojure) 등이 있다. 이런 함수형 언어는 단순화된 구조로 입력과 출력을 가능하게 하는 익명화된 함수 표기법인 ‘람다식’을 사용한다.


파워자바

24장 입출력


스트림(Stream)

순서가 있는 데이터의 연속적인 흐름

입출력을 물의 흐름으로 간주


스트림들은 연결될 수 있다


입출력 스트림 - 바이트 스트림, 문자 스트림

바이트 스트림 - 입력 바이트 스트림(Input Stream), 출력 바이트 스트림(Output Stream)

문자 스트림 - 입력 문자 스트림(Reader), 출력 문자 스트림(Writer)


데이터 처리 스트림

버퍼링 - 문자 스트림(BufferedReader, BufferedWriter), 바이트 스트림(BufferedInputStream, BufferedOutputStream)


바이트 스트림

InputStream - FileInputStream, PipedInputStream, ByteArrayInputStream, StringBufferInputStream

OutputStream - FileOutputStream, PipedOutputStream, ByteArrayOutputStream


InputStream과 OutputStream

추상 클래스로서 모든 바이트 스트림의 조상 클래스


FileInputStream과 FileOutputStream

파일이 입출력 대상이 된다


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.io.*;
 
public class FileStreamTest {
    public static void main(String[] args) throws IOException {
        FileInputStream in = null;
        FileOutputStream out = null;
        int c;
        try {
            out = new FileOutputStream("data.txt"false);
            for(int i=0;i<10;i++){
                out.write(i);
            }
            in = new FileInputStream("data.txt");
            while((c=in.read())!=-1) {
                System.out.println(c+"");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(in != null) {
                in.close();
            }
            if(out != null) {
                out.close();
            }
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.io.*;
 
public class FileStreamTest {
    public static void main(String[] args) throws IOException {
        int c;
        FileOutputStream out = null;
        FileInputStream in = null;
        try {
            out = new FileOutputStream("data.txt"false);
            for(int i=0;i<10;i++){
                out.write(i);
            }
            out.close(); // out 계열 close가 구동이 돼야 write가 완료됨
            in = new FileInputStream("data.txt");
            while((c=in.read())!=-1) {
                System.out.print(c+" ");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(in != null) {
                in.close();
            }
            if(out != null) {
                out.close();
            }
        }
    }
}
 
cs



DataInputStream과 DataOutputStream 클래스는 기초 자료형 단위로 데이터를 읽고 쓸 수 있다

ObjectInputStream과 ObjectOutputStream

직렬화(serialization)

객체가 가진 데이터들을 순차적인 데이터로 변환하는 것


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.io.*;
import java.util.Date;
 
public class ObjectStreamTest {
    public static void main(String[] args) throws IOException {
        ObjectInputStream in = null;
        ObjectOutputStream out = null;
        int c;
        try {
            out = new ObjectOutputStream(new FileOutputStream("object.dat"));
            out.writeObject(new Date());
            out.flush();
            in = new ObjectInputStream(new FileInputStream("object.dat"));
            Date d = (Date) in.readObject();
            System.out.println(d);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (in != null){
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
}
 
cs


InputStreamReader와 OutputStreamWriter

바이트 스트림과 문자 스트림을 연결하는 클래스


바이트 스트림 -> InputStreamReader -> 문자 스트림

문자 스트림 <- OutputStreamReader <- 바이트 스트림


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.io.*;
 
public class FileStreamTest {
    public static void main(String[] args) throws IOException {
        int c;
        FileOutputStream out = null;
        FileInputStream in = null;
        InputStreamReader ins = null;
        try {
            out = new FileOutputStream("data.txt"false);
            for(int i=0;i<10;i++){
                out.write(i);
            }
            out.close(); // out 계열 close가 구동이 돼야 write가 완료됨
            in = new FileInputStream("data.txt");
            ins = new InputStreamReader(in);
            while((c=ins.read())!=-1) {
                System.out.print(c+" ");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(in != null) {
                in.close();
            }
            if(out != null) {
                out.close();
            }
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.io.*;
 
public class FileStreamTest {
    public static void main(String[] args) {
        // 쓰기 메모장에 write
        try {
            // Write
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("abc.txt")));
            bw.write("Hello Stream~");
            bw.close(); // 닫아줘야 써짐. Bug 발생 유의할 것
 
            // Read
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("abc.txt")));
            String str;
            while((str = br.readLine())!=null){
                System.out.println(str);
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
cs


람다식

익명 메서드와 파라미터 전달의 형태로 표현한다.


(파라미터 목록) -> {구문}


msg를 출력하는 간단한 메서드

public void printMsg(String msg) {

System.out.println(msg);

}

이를 람다식으로 변경하면

(String msg) -> {System.out.println(msg);}


함수형 인터페이스

함수형 인터페이스는 자바 8에 추가된 구조로, 메서드가 하나만 있는 인터페이스를 말한다


button.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

...

}

});


button.addActionListener((e) -> {...});


1
2
3
4
5
6
7
8
9
public class Main {
    public static void main(String[] args) {
        new Thread(()->{
            System.out.println("Hello");
            System.out.println(Thread.currentThread().getName());
        }).start();
    }
}
 
cs


list라는 ArrayList의 모든 데이터 출력


for(Integer num : list) {

System.out.println(num);

}


list.forEach(n -> {System.out.println(n);};


파워자바

제 27장 데이터베이스 프로그래밍


자바와 데이터베이스

JDBC(Java Database Connectivity)는 자바 API의 하나로서 데이터베이스에 연결하여서 데이터베이스 안의 데이터에 대하여 검색하고 데이터를 변경할 수 있게 한다.


SQL

데이터 정의 명령어DDL

CREATE, ALTER, DROP, USE

데이터 조작 명령어DML

SELECT, INSERT, DELETE, UPDATE


인텔리J

build.gradle 클릭


gradle의 dependencies에

11은

implementation group: 'com.oracle.database.jdbc', name: 'ojdbc11', version: '21.1.0.0'

8이라서

implementation group: 'com.oracle.database.jdbc', name: 'ojdbc8', version: '21.1.0.0'

추가


구글링 maven jdbc driver dependency

mvnrepository 클릭


CREATE TABLE books (

book_id INT NOT NULL PRIMARY KEY,

title VARCHAR2(50),

publisher VARCHAR2(30),

year VARCHAR2(10),

price INT

);


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.sql.*;
 
public class JDBCMain {
    public static Connection makeConnection() {
        // 1. DB접속
        // -Connection 클래스
        Connection conn = null;
 
        // 2. 연결 문자열 생성
        // -접속에 필요한 정보로 구성된 문자열, Connection String
        String url = "jdbc:oracle:thin:@localhost:1521:xe"//localhost대신 ip주소가 들어갈수도
        String id = "hr";
        String pw = "hr";
 
        // DB작업 > 외부 입출력 > try-catch 필수
 
        try {
// 3. JDBC 드라이버 로딩
            Class.forName("oracle.jdbc.driver.OracleDriver");
            System.out.println("드라이버 적재 성공");
            // 4. 접속
            // - Connection 객체 생성 + 접속 작업.
            conn = DriverManager.getConnection(url, id, pw);
            System.out.println("데이터베이스 연결성공");
 
            // 5. SQL
            String query = "INSERT INTO books (book_id, title, publisher, year, price) " +
                    "VALUES (BOOK_SEQ.nextval, ?, ?, ?, ?)";
 
            //PreparedStatement로 쿼리 수행
            PreparedStatement pstmt = conn.prepareStatement(query);
            pstmt.setString(1"Operating System Concepts");
            pstmt.setString(2"Wiley");
            pstmt.setString(3"2003");
            pstmt.setInt(4,30700);
 
            int ret = pstmt.executeUpdate();
            System.out.println(ret);
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
 
    }
    public static void main(String[] args) {
        try {
            Connection con = makeConnection();
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM books");
            while(rs.next()){
                int id = rs.getInt("book_id");
                String title = rs.getString("title");
                System.out.println(id + " " + title);
            }
            con.close();
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
    }// main
}
cs


728x90
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기