728x90

 기본 환경: IDE: Eclipse, Language: Java

 

 

발생 Exception

Java에서 다음 Source Code를 실행할 경우,

package io;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;

public class ObjectMain {
	public static void main(String[] args) throws IOException {
		PersonDTO pDTO = new PersonDTO("홍길동", 25, 185.3);
		
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("result.txt"));
		oos.writeObject(pDTO);
		oos.close();
		
	}
}

java.io.NotSerializableException 발생

 

 

Exception 원인

입출력 처리 시, Object(객체)는 파일이나 네트워크로 전송이 되지 않음

객체를 byte[]화하여, 전송해야 함(Serializable)

 

 

해결 방법

Object type인 PersonDTO class에서 Serializable interface 구현

package io;

import java.io.Serializable;

public class PersonDTO implements Serializable { // abstract method X

	private String name;
	private int age;
	private double height;

	public PersonDTO(String name, int age, double height) {
		this.name = name;
		this.age = age;
		this.height = height;
	}
	
	public void setName(String name) {this.name = name;}
	public void setAge(int age) {this.age = age;}
	public void setHeight(double height) {this.height = height;}
	
	public String getName() {return name;}
	public int getAge() {return age;}
	public double getHeight() {return height;}
	
}
package io;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;

public class ObjectMain {
	public static void main(String[] args) throws IOException {
		PersonDTO pDTO = new PersonDTO("홍길동", 25, 185.3);
		
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("result.txt"));
		oos.writeObject(pDTO);
		oos.close();
		
	}
}

/*
Result
Name: 홍길동
Age: 25
Height: 185.3
*/

 

728x90
728x90

 기본 환경: IDE: Eclipse, Language: Java

 

 

발생 Exception

Java에서 다음 Source Code를 실행할 경우,

public class StrFormat {
    
    public static void main(String[] args) {
        double d = 2.3;
        System.out.println(String.format("%.2d", d));
    }

}

⭐ java.util.IllegalFormatPrecisionException: 2 발생

 

 

Exception 원인

String.format: %d: 10진수 int type

int type data format으로 doubloe or float type data로 표현하고자 함

 

 

해결 방법

1. 실수 type data format으로 변경

public class StrFormat {
    
    public static void main(String[] args) {
        double d = 2.3;
        System.out.println(String.format("%.2f", d));
    }

}

/*
Result
2.30
*/

 

2. 정수 type data format에 맞추기

: (cast) double type data -> int type

: int data 표현 방식으로 변경

public class StrFormat {
    
    public static void main(String[] args) {
        double d = 2.3;
        System.out.println(String.format("%02d", (int) d));
    }

}

/*
Result
02
*/
728x90
728x90

 기본 환경: IDE: Eclipse, Language: Java

 

 

발생 Exception

Java에서 다음 Source Code를 실행할 경우,

public class SungJukDelete_T implements SungJuk {
	Scanner scan = new Scanner(System.in);
	
	@Override
	public void execute(ArrayList<SungJukDTO> arrayList) {
		System.out.print("삭제할 이름 입력: ");
		String name_del = scan.next();

		int count=0;
		for(SungJukDTO sungJukDTO : arrayList) {
			if(sungJukDTO.getName().equals(name_del)) {
				arrayList.remove(sungJukDTO);
				count++;
			}
		}

		if(count==0) {System.out.println("There is no Memeber in the list.");}
		else {System.out.println(count + " member deleted");}

	}
	
}

⭐ java.lang.Error:  java.util.ConcurrentModificationException 발생

 

 

Exception 원인

for문 실행 시, 고정된 arrayList size가 remove()를 통해 size()가 변경되어 Exception 발생

➕ 추가적인 문제

i=0
arrayList[0] = aaa;
arrayList[1] = aaa;
arrayList[2] = bbb;
-> idx 변경
i=1
arrayList[0] = aaa;
arrayList[1] = bbb;
-> idx=0인 arrayList의 aaa data를 삭제할 수 없음

 

 

해결 방법

데이터의 크기가 변경되어도 프로그램 작동에 영향을 미치지 않는 Iterator interface 활용

public class SungJukDelete_T implements SungJuk {
	Scanner scan = new Scanner(System.in);
	
	@Override
	public void execute(ArrayList<SungJukDTO> arrayList) {
		System.out.print("삭제할 이름 입력: ");
		String name_del = scan.next();

		int count=0;
		
		Iterator<SungJukDTO> iterator = arrayList.iterator();
		// iterator는 idx num과 무관

		while(iterator.hasNext()) {
			SungJukDTO sjDTO = iterator.next();
			// arrayListd에 항목을 꺼내서 sjDTO에 보관
			// iterator 다음 항목으로 이동
			
			if(sjDTO.getName().equals(name_del)) {
				iterator.remove();
				// remove(): iterator가 remove 전 꺼내놓은 항목(Buffer에 저장한 항목)을 제거
				// Buffer에 저장된 값을 제거하는 것이므로 next()를 사용하지 않으면 remove()를 사용할 수 없음
				count++;
			}
			
		}


		if(count==0) {System.out.println("There is no Memeber in the list.");}
		else {System.out.println(count + " member deleted");}

	}
	
}

⭐ index를 통해 원본 데이터를 제거하면서 원본 데이터를 사용하는 방식이 아닌,

Buffer에 따로 저장해놓고 데이터를 간접적으로 삭제하는 방식을 취함으로 ConcurrentModificationException을 해결할 수 있음

728x90
728x90

 기본 환경: IDE: Eclipse, Language: Java

 

 

발생 Exception

Java에서 다음 Source Code를 실행할 경우,

public class RandomChar {

	public static void main(String[] args) {
        char[] ar = new char[50];
		int[] count = new int[26]; // Default=0

		for(int i = 0; i<ar.length; i++) {
			ar[i] = (char)(Math.random()*26) + 65;
			if(i%10==0) {System.out.println();}
			System.out.print(ar[i] + " ");

			for(int j=0; j<count.length; j++) {
				if(j == (ar[i]-65)) {count[j]++;};
			} // for inner
			
		} // for outer
    }
}

⭐ java.lang.Error: Unresolved compilation problem:

→  Type mismatch: cannot convert from int to char 발생

 

 

Exception 원인

cast char값에 int를 더해줄 수 없음

ar[i] = (char)(Math.random()*26) + 65;

계산 순서

Math.random()*26 : int

(char) (Math.random()*26): char

(char) (Math.random()*26)+65: char + int

char type으로 강제 형 변환 후, int를 직접적으로 더해줄 수 없음

 

⭐ 일반적으로 char + int -> int 변환이 이뤄지는데, 해당 source code에서만 예외적으로 실행되지 않음

public class CharIntDouble {

	public static void main(String[] args) {

        int a = 70;
        char b = 'A';
        double c = 66.7;

        System.out.println(a);
        System.out.println(b);
        System.out.println(a+2);
        System.out.println(b+2);
        System.out.println((char)a+2);
        System.out.println((int)c);
        System.out.println((char)c);
        System.out.println((char)c+10);

    }
}

/*
Result
70
A
72
67 : char + int = int
72 : char + int = int
66
B
76 : char + int = int
*/

 

 

해결 방법

+65를 괄호안으로 넣어 계산 순서 변경

public class delete {

	public static void main(String[] args) {
        char[] ar = new char[50];
		int[] count = new int[26]; // Default=0

		for(int i = 0; i<ar.length; i++) {
			ar[i] = (char)(Math.random()*26 + 65);
			if(i%10==0) {System.out.println();}
			System.out.print(ar[i] + " ");

			for(int j=0; j<count.length; j++) {
				if(j == (ar[i]-65)) {count[j]++;};
			} // for inner
			
		} // for outer
    }
}

/*
Result
Q Q C P N B P G O J 
O C Z G F G U O A F
Q H S Q U K E U Q R
L I Y E Y K M O K H
R Y Z C S S F Z Q N

*/

 

728x90
728x90

 기본 환경: IDE: Eclipse, Language: Java

 

 

발생 Exception

Java에서 다음 Source Code를 실행할 경우,

import java.util.*;
import java.text.*;

public class Today {

	public static void main(String[] args) {
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss"); // java.text
		Date birth = sdf2.parse("20230213184030"); // java.util, String -> Date 형변환
		System.out.println("Birth: " + sdf2.format(birth));
		
	}
	
}

⭐ java.lang.Error: Unresolved compilation problem:

→ Unhandled exception type ParseException 발생

 

 

Exception 원인

문자열을 기반으로 객체를 만드는데 파싱*에서 에러가 발생할 경우, ParseException이 발생

*파싱(Parsing): 구문 분석, 주어진 정보를 내가 원하는 형태로 가공하는 것

Source Code상의 문제는 없으나, Compile Error가 발생할 수 있기때문에 Exception에 대한 처리 필요

 

 

해결 방법

1. Add throws declaration

import java.util.*;
import java.text.*;

public class Today {

	public static void main(String[] args) throws ParseException {
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss"); // java.text
		Date birth = sdf2.parse("20230213184030"); // java.util, String -> Date 형변환
		System.out.println("Birth: " + sdf2.format(birth));
		
	}
	
}

 

2. Surround with try/catch

import java.util.*;
import java.text.*;

public class Today {

	public static void main(String[] args) {
		Date date = new Date();
		System.out.println("오늘 날짜: " + date);
		
		SimpleDateFormat sdf = new SimpleDateFormat("y년 MM월 dd일 E요일 HH:mm:ss");
		System.out.println("오늘 날짜: " + sdf.format(date));
		
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss"); // java.text

		Date birth=null;
		try {
			birth = sdf2.parse("20230213184030");
		} catch (ParseException e) {
			e.printStackTrace();
		} // java.util, String -> Date 형변환
		System.out.println("Birth: " + sdf2.format(birth));
	}
	
}

 

 

 

참고 자료

📑 Live Study 9주차 - 예외 처리

📑 [JAVA] Parsing이란 무엇인가?

 

728x90