1. Consider the Java code identified below. Does this code use a checked or unch
ID: 3721753 • Letter: 1
Question
1. Consider the Java code identified below. Does this code use a checked or unchecked exception? How do you know? In your answer explain the difference between a checked and unchecked exception.
public static void sampleMethod() throws IOException {
// Other Method Code
if (error) {
throw new IOException("TEST");
}
}
2. Consider the following Java code representing a partially completed Actor data definition class. Write an accessor method for the instance variable, movieNames.
public class Actor {
private String name;
private int age;
private String[] movieNames;
private static int numActors;
}
3. Consider the block of Java code identified below meant to read an input file. What code should be inserted in between the ** ** symbols? Explain why this code should be inserted. public static void main(String[] args) **____________________** {
Scanner in = new Scanner(new FileInputStream((new File(aFile.getSelectedFile().getPath()))));
// remaining method code
}
Explanation / Answer
Q1)
Answer)
The above code handles a Checked Exception which is an IOException. In the above code snippet, when the //Other Method Code gives an error or exception, then according to our understanding we presume that it'll be none other than an IOException and thus we handle it using a if block and throwing the exception as:
throw new IOException("TEST");
and also the method throws the exception as:
throws IOException
Thus this handles a checked exception as the Exception is checked at compile time.
Difference between a checked and unchecked exception:
A checked exception in Java are the exceptions that are checked at compile time and thus can be handled in the code by using try catch block or specify the exception using throws keyword and throwing the exception.
An unchecked exception on the other hand are the exceptions which are not checked at the compile time and are thus unchecked. Error and RuntimeException classes in Java are unchecked exceptions.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.