/* numbers.txt contains numbers. After reading number from file, prints its square on console */import java.io.*;
publicclassMCatchDemo {
publicstaticvoidmain(String args[]) {
try {
// may throw FileNotFound & IOException FileReader fr =new FileReader("numbers.txt");
BufferedReader br =new BufferedReader(fr);
// read the line String s = br.readLine();
// may throw NumberFormatException, if s is not no.int number = Integer.parseInt(s);
System.out.println(number * number);
} catch (NumberFormatException nfEx) {
System.out.println(nfEx);
} catch (FileNotFoundException fnfEx) {
System.out.println(fnfEx);
} catch (IOException ioEx) {
System.out.println(ioEx);
} finally {
br.close();
}
}
}
We read everything from a file (numbers, floating values or text) as a String. That’s why we first convert it to numb and then print its square on console.
Compile & Execute
If file numbers.txt is not present in the same directory, the FileNotFoundException would be thrown during execution.
The ThrowsDemo.java contains two methods namely method1 & method2 and one main method. The main method will make call to method1 and than method1 will call method2. The method2 contains the file reading code. The program looks like one given below
If file strings.txt is not present in the same directory, method2 will throw an exception that would be caught by method1 and the printStackTrace method will print the full calling history on console. The above scenario is shown in the output below:
classOutOfRangeextends Exception {
privateint min;
privateint max;
publicOutOfRange(int min, int max) {
this.min= min;
this.max= max;
}
@Override
public String getMessage() {
return"Number must be between "+ min +" and "+ max;
}
}
Exercise:
Write a program in java that takes in a value from a user to find the square of an integer from 0 to 100. If the value is not an integer or within the range, then print the exception. To handle the outOfRange exception, create a custom exception class that can be thrown in case a number is out of range.
If your instructor is using GitHub classroom, then you should click on your class submission link,
link your GitHub username to your name if you have not already done so, accept the assignment, clone the
repository into your local
development environment, and push the code to the remote repository on GitHub. Please make sure that your
written
answers are included in either a README (Markdown) file or a PDF file.
Lab dues dates are listed on GitHub classroom unless otherwise
noted.
If your instructor is using GitHub classroom, your submission will be
auto-graded
by running the included unit tests as well as manually graded for correctness, style, and quality.
How to submit your lab to GitHub Classroom
The video below demonstrates how to submit your work to GitHub classroom