JetBrains Academy: Exception handling - Kamil-Jankowski/Learning-JAVA GitHub Wiki
JetBrains Academy: Exception handling
String to double conversion:
Consider a method that takes a string and converts it to a double. If the input string happen to be null or of an unsuitable format, a runtime exception occurs and the program fails.
Fix the method so it would catch any exceptions and return the default value 0 (zero) if an exception occurred.
public static double convertStringToDouble(String s) {
double d = 0.0;
try {
d = Double.parseDouble(s);
} catch (RuntimeException e){
d = 0.0;
}
return d;
}
Catching exceptions of the specified types:
Consider the two methods: methodThrowingExceptions
and methodCatchingSomeExceptions
.
The first one throws unchecked exceptions of different types.
Your task is to implement the second method. It must call the first method and catch two types of exceptions:
ArrayIndexOutOfBoundsException
NumberFormatException
Inside the catch block (or blocks) you should print the name of the handled exception class (only name, without packages) to the standard output.
Other types of exceptions must not be caught by the methodCatchingSomeExceptions
.
public static void methodCatchingSomeExceptions() {
try {
methodThrowingExceptions();
} catch (ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
} catch (NumberFormatException e){
System.out.println("NumberFormatException");
}
}
Converting a sequence of numbers:
Your task is to write a program that reads a sequence of strings and converts them to integer numbers, multiplying by 10. Some input strings may have an invalid format, for instance: "abc". The sequence is ended by the 0 (zero).
If a string can be converted to an integer number, output the number multiplied by 10. Otherwise, output the string "Invalid user input: X" where X is the input string. To better understand see examples below.
To implement this logic, use the exception handling mechanism.
Input data format is a sequence of integer numbers and other strings, each in a new line.
Output data format is a sequence of integer numbers and warnings, each in a new line.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String temp = scanner.nextLine();
String inputs = "";
while (!"0".equals(temp)){
inputs += temp + " ";
temp = scanner.nextLine();
}
String[] elements = inputs.split(" ");
for (String i : elements){
try {
System.out.println(Integer.parseInt(i) * 10);
} catch (Exception e){
System.out.printf("Invalid user input: %s\n", i);
}
}
}
}