카테고리 없음

31. JAVA 예제 정리 [예외처리]

woogy99 2024. 12. 18. 17:16

package com.sist.exception;

 

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

 

/*

1. 이벤트 처리

 

*/

public class 숫자야구게임 extends JFrame implements ActionListener {

JTextArea ta; // 힌트 출력

JTextField tf;

JButton b1, b2;

 

int[] com = new int[3];

int[] user = new int[3];

 

// 초기화 => 생성자 , 초기화 블록

public 숫자야구게임() {

ta = new JTextArea();

JScrollPane js = new JScrollPane(ta);

ta.setEditable(false); // 편집방지

tf = new JTextField(10);

tf.setEditable(false); // 비활성화

b1 = new JButton("시작");

b2 = new JButton("종료");

 

// 배치

JPanel p = new JPanel();

p.add(tf);

p.add(b1);

p.add(b2);

 

add("Center", js);

add("South", p);

setSize(350, 300);

setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);

 

// 이벤트 등록

b1.addActionListener(this);

// 자신이 가지고 있는 actionPerformd();

// 마우스 => addMouseListener()

b2.addActionListener(this);

tf.addActionListener(this);

}

 

public static void main(String[] args) {

// TODO Auto-generated method stub

new 숫자야구게임();

 

}

 

public void getRand() {

for (int i = 0; i < com.length; i++) {

com[i] = (int) (Math.random() * 9) + 1;

 

for (int j = 0; j < i; j++) {

 

if (com[i] == com[j]) {

i--; // 원래 인덱스로 돌려줌

break;

}

}

}

}

 

@Override

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

if (e.getSource() == b2) { // b2 버튼을 클릭했다면

 

int sel = JOptionPane.showConfirmDialog(this, "종료할까요?", "종료", JOptionPane.YES_NO_OPTION);

 

if (sel == JOptionPane.YES_OPTION) {

System.exit(0);

}

} else if (e.getSource() == b1) {

getRand();

tf.setEditable(true);

tf.requestFocus();

b1.setEnabled(false);

} else if (e.getSource() == tf) {

try {

// 입력된 데이터 읽기

String str = tf.getText();

int input = Integer.parseInt(str);

 

if (input < 100 || input > 999) {

JOptionPane.showMessageDialog(this, "3자리 정수만 입력");

tf.setText("");

tf.requestFocus();

return;// 메소드 종료

}

user[0] = input / 100;

user[1] = (input % 100) / 10;

user[2] = input % 10;

 

if (user[0] == user[1] || user[1] == user[2] || user[0] == user[2]) {

JOptionPane.showMessageDialog(this, "중복 수는 사용할 수 없습니다");

tf.setText("");

tf.requestFocus();

return;// 메소드 종료

}

if (user[0] == 0 || user[1] == 0 || user[2] == 0) {

JOptionPane.showMessageDialog(this, "0은 사용할 수 없습니다.");

tf.setText("");

tf.requestFocus();

return;// 메소드 종료

}

 

// 비교

int s = 0, b = 0;

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

 

if (com[i] == user[j]) {

if (i == j) {

s++;

} else {

b++;

}

}

}

}

String hint = "Input Number : " + input + ",Result: " + s + "S-" + b + "B\n";

 

ta.append(hint);

 

if(s==3) {// 종료 여부 확인

JOptionPane.showMessageDialog(this, "프로그램을 종료합니다");

System.exit(0);

}

tf.setText("");

tf.requestFocus();

// 3자리가 아닌 경우 처리

} catch (NumberFormatException ex) {

JOptionPane.showMessageDialog(this, "세자리 정수만 입력해야 됩니다.");

tf.setText("");

tf.requestFocus();

// 예외복구 => RuntimeException

// 예외처리가 없어도 가능 (UnCheck)

// 필요에 의해 처리

// => UnCheckException

}

}

}

 

}

 


package com.sist.exception;

 

/*

변수 => 데이터형

연산자 / 제어문

배열 => 1차원

클래스 /객체 생성 / 메소드

상속 / 오버라이딩

인터페이스

라이브러리 => 조립

=> Collection / IO

------------------------- 웹

==12장 필수 (오라클)

 

8장 예외처리

 

목적 : 사전에 에러를 방지하는 목적

우선시 => if

-------> 처리가 어려운 경우 : 예외처리 사용

=> 비정상 종료를 방지하고 정상상태 유지

=> 예외처리 => 에러 발생시 에러를 건너뛴다

------ if

 

에러발생

사용자 => 잘못된 입력 => 유효성 검사 => if(javascript)

개발자 => 실수 => 배열 인덱스 , 정수 변환, 형변환

-------------------------------------------

컴파일 인터프리터

A.java =======> A.class =======> 화면 출력

javac java

| |

에러 에러

------예외처리

실시간 에러

RuntimeException

=> 경우에 따라 예외처리

확인) 컴파일시에 반드시 예외처리가 필요

=> CheckException : 필수적으로 예외처리

= IO(파일입출력)

IOException

= 네트워크 (서버 => URL, IP)

MalformedURLexception

= SQL (데이터베이스)

SQLException

= 쓰레드

InterruptedExcetion

=> UnCheckException : 필요시에만 예외처리 ==>

배열범위 초과 / 정수 변환 / 0으로 나누는 경우

객체가 null / 클래스 형변환...

 

 

1) 사전에 차단 ( 우선시 => if) => 예외처리

2) 에러

=에러 => 소스상에서 수정이 불가

메모리 부족, 이클립스

치명적 에러 => 처리가 불가능

 

=예외처리 => 소스상에서 수정이 가능 에러

예) 파일읽기 => 경로명/ 파일명 다른 경우

데이터베이스 => SQL 문장 틀린 경우

크롤링 => URL 주소가 다른 경우

배열 인덱스가 틀린 경우

3) 예외처리 방법

= 예외복구 : try ~ catch

---- ----- 예외가 발생시 처리 복구

정상수행

= 예외회피 (떠맡기기) : throws

= 임의 발생 => 견고한 프로그램 여부 확인

= 지원하지 않는 예외 : 사용자 정의 예외처리

--------------

public class MyException extends Exception

{

}

예외처리를 하는 경우

---------------- 예외가 많이 예상되는 경우

catch를 여러개 사용이 가능

--------------------- 순서가 존재

 

문자열 => 정수로 변경후에 배열에 저장 => 나눈값을 출력

 

=> 사전에 에러방지 => 에러 예상하면서 소스코딩.

 

 

ClassNotFoundException

InterrutedException

MalformedUR

 

 

 

*/

public class 예외처리_1 {

 

public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

Thread.sleep(10);

 

for (int i = 1; i <= 10; i++) {

try {

int r = (int) (Math.random() * 3);

int a = 1 / r;

System.out.println("i=" + i + ",a" + a);

 

} catch (Exception e) {

// TODO: handle exception

}

}

 

}

}


package com.sist.exception;

 

public class 예외처리_2 {

public static void main(String[] args) {

for (int i = 1; i <= 10; i++) {

try {

int r = (int) (Math.random() * 3);

int a = 1 / r;

System.out.println("i=" + i + ",a" + a);

 

} catch (Exception e) {

// TODO: handle exception

}

}

}

}

 

 

package com.sist.exception;

 

public class 예외처리_3 {

 

public static void main(String[] args) {

// TODO Auto-generated method stub

System.out.println("문장 1");

System.out.println("문장 2");

System.out.println("문장 3");

try {

System.out.println("문장 4");

System.out.println("문장 5");

System.out.println("문장 6");

} catch (Exception e) {

// TODO: handle exception

System.out.println("문장 7");

}

System.out.println("문장 8");

System.out.println("문장 9");

}

 

}

 

package com.sist.exception;

 

import java.util.Scanner;

 

public class 예외처리_4 {

 

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner scan = new Scanner(System.in);

int[] arr = new int[2];

try {

 

System.out.print("첫번째 정수 입력 : ");

String s1 = scan.next();

System.out.print("두번째 정수 입력 : ");

String s2 = scan.next();

 

arr[0]=Integer.parseInt(s1);

arr[1]=Integer.parseInt(s2);

int result = arr[0] / arr[1];

System.out.println("result" + result);

} catch (ArrayIndexOutOfBoundsException e) {

// TODO: handle exception

//System.out.println(e.getMessage());

e.printStackTrace();

 

} catch (ArithmeticException e) {

// TODO: handle exception

//System.out.println(e.getMessage());

e.printStackTrace();

} catch (NumberFormatException e) {

// TODO: handle exception

//System.out.println(e.getMessage());

e.printStackTrace();

}

System.out.println("정상 수행");

}

 

}

 

package com.sist.exception;

 

import java.util.Arrays;

 

public class 예외처리_CheckExcption_예제_1 {

public static void main(String[] args) {

try {

int[] lotto = new int[6];

for (int i = 0; i < lotto.length; i++) {

lotto[i]=(int)(Math.random()*45)+1;

for (int j = 0; j < i; j++) {

if (lotto[i] == lotto[j]) {

i--;

break;

}

}

}

 

Arrays.sort(lotto);

 

for(int i:lotto) {

Thread.sleep(1000);

System.out.println(i+" ");

 

}

 

} catch (InterruptedException e) {

e.printStackTrace();

} finally {

System.out.println("프로그램 종료");

}

}

 

}