Computer Science, asked by sanjaykhanna5337, 1 year ago

Which class do checked exceptions inherit from?

Answers

Answered by Neerajchauhan1
0
A checked exception is a type of exception that must be either caught or declared in the method in which it is thrown. For example, the java.io.IOException is a checked exception. To understand what is a checked exception, consider the following code:

Code section 6.9: Unhandled exception.

1 public void ioOperation(boolean isResourceAvailable) { 2 if (!isResourceAvailable) { 3 throw new IOException(); 4 } 5 }

This code won't compile because it can throw a checked exception. The compilation error can be resolved in either of two ways: By catching the exception and handling it, or by declaring that the exception can be thrown using the throws keyword.

Code section 6.10: Catching an exception.

1 public void ioOperation(boolean isResourceAvailable) { 2 try { 3 if (!isResourceAvailable) { 4 throw new IOException(); 5 } 6 } catch(IOException e) { 7 // Handle caught exceptions. 8 } 9 }

Code section 6.11: Declaring an exception.

1 public void ioOperation(boolean isResourceAvailable) throws IOException { 2 if (!isResourceAvailable) { 3 throw new IOException(); 4 } 5 }

In the Java class hierarchy, an exception is a checked exception if it inherits from java.lang.Throwable, but not from java.lang.RuntimeException or java.lang.Error. All the application or business logic exceptions should be checked exceptions.

It is possible that a method declares that it can throw an exception, but actually it does not. Still, the caller has to deal with it. The checked exception declaration has a domino effect. Any methods that will use the previous method will also have to handle the checked exception, and so on.

So the compiler for the Java programming language checks, at compile time, that a program contains handlers for all application exceptions, by analyzing each method body. If, by executing the method body, an exception can be thrown to the caller, that exception must be declared. How does the compiler know whether a method body can throw an exception? That is easy. Inside the method body, there are calls to other methods; the compiler looks at each of their method signature, what exceptions they declared to throw.

Similar questions