본문 바로가기

[JAVA] 개발

Java Software Solution Ch11_ PP1 ; Exception Class (try-catch)

PP 11.1

Write a program that creates an exception class called StringTooLongException, designed to be thrown when a string is discovered that has too many characters in it. In the main driver of the program, read strings from the user until the user enters "DONE". If a string is entered that has too many characters (say 20), throw the exception. Allow the thrown exception to terminate the program.

 

PP11_1.java

import java.util.Scanner;

public class PP11_1 {
	public static void main(String[] args) throws
		// TODO Auto-generated method stub
		StringTooLongException{
			Scanner scanner = new Scanner(System.in);
			String str;
			try {
				System.out.print("String (If you want stop, 'DONE') : ");
				str = scanner.nextLine();
				while(!str.equals("DONE")) {
					if(str.length()>20) { throw new StringTooLongException(); }
					System.out.print("String (If you want stop, 'DONE') : ");
					str = scanner.nextLine();
				}
			} catch (StringTooLongException st) { System.out.println("The characters are 20 or more."+ st);
		}
	}
}

 

StringTooLongException.java

public class StringTooLongException extends Exception{
	public StringTooLongException() { super(""); }
}

 

< Console >

String (If you want stop, 'DONE') : SE111
String (If you want stop, 'DONE') : CHAPTER 8
String (If you want stop, 'DONE') : HOMEWORK 8
String (If you want stop, 'DONE') : PP 11.1
String (If you want stop, 'DONE') : OBJECT-ORIENTED PROGRAMMING
The characters are 20 or more.ch8.StringTooLongException: