Why is "throws Exception" necessary when calling a function? - java

class throwseg1
{
void show() throws Exception
{
throw new Exception("my.own.Exception");
}
void show2() throws Exception // Why throws is necessary here ?
{
show();
}
void show3() throws Exception // Why throws is necessary here ?
{
show2();
}
public static void main(String s[]) throws Exception // Why throws is necessary here ?
{
throwseg1 o1 = new throwseg1();
o1.show3();
}
}
Why compiler reports that methods show2(), show3(), and main() have
unreported exception Exception that must be caught or declared to be thrown
when I remove throws Exception from these methods?

In Java, as you may know, exceptions can be categorized into two: One that needs the throws clause or must be handled if you don't specify one and another one that doesn't. Now, see the following figure:
In Java, you can throw anything that extends the Throwable class. However, you don't need to specify a throws clause for all classes. Specifically, classes that are either an Error or RuntimeException or any of the subclasses of these two. In your case Exception is not a subclass of an Error or RuntimeException. So, it is a checked exception and must be specified in the throws clause, if you don't handle that particular exception. That is why you needed the throws clause.
From Java Tutorial:
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
Now, as you know exceptions are classified into two: checked and unchecked. Why these classification?
Checked Exception: They are used to represent problems that can be recovered during the execution of the program. They usually are not the programmer's fault. For example, a file specified by user is not readable, or no network connection available, etc., In all these cases, our program doesn't need to exit, instead it can take actions like alerting the user, or go into a fallback mechanism(like offline working when network not available), etc.
Unchecked Exceptions: They again can be divided into two: Errors and RuntimeExceptions. One reason for them to be unchecked is that they are numerous in number, and required to handle all of them will clutter our program and reduce its clarity. The other reason is:
Runtime Exceptions: They usually happen due to a fault by the programmer. For example, if an ArithmeticException of division by zero occurs or an ArrayIndexOutOfBoundsException occurs, it is because we are not careful enough in our coding. They happen usually because some errors in our program logic. So, they must be cleared before our program enters into production mode. They are unchecked in the sense that, our program must fail when it occurs, so that we programmers can resolve it at the time of development and testing itself.
Errors: Errors are situations from which usually the program cannot recover. For example, if a StackOverflowError occurs, our program cannot do much, such as increase the size of program's function calling stack. Or if an OutOfMemoryError occurs, we cannot do much to increase the amount of RAM available to our program. In such cases, it is better to exit the program. That is why they are made unchecked.
For detailed information see:
Unchecked Exceptions — The Controversy
The Catch or Specify Requirement

Java requires that you handle or declare all exceptions. If you are not handling an Exception using a try/catch block then it must be declared in the method's signature.
For example:
class throwseg1 {
void show() throws Exception {
throw new Exception();
}
}
Should be written as:
class throwseg1 {
void show() {
try {
throw new Exception();
} catch(Exception e) {
// code to handle the exception
}
}
}
This way you can get rid of the "throws Exception" declaration in the method declaration.

The throws Exception declaration is an automated way of keeping track of methods that might throw an exception for anticipated but unavoidable reasons. The declaration is typically specific about the type or types of exceptions that may be thrown such as throws IOException or throws IOException, MyException.
We all have or will eventually write code that stops unexpectedly and reports an exception due to something we did not anticipate before running the program, like division by zero or index out of bounds. Since the errors were not expected by the method, they could not be "caught" and handled with a try catch clause. Any unsuspecting users of the method would also not know of this possibility and their programs would also stop.
When the programmer knows certain types of errors may occur but would like to handle these exceptions outside of the method, the method can "throw" one or more types of exceptions to the calling method instead of handling them. If the programmer did not declare that the method (might) throw an exception (or if Java did not have the ability to declare it), the compiler could not know and it would be up to the future user of the method to know about, catch and handle any exceptions the method might throw. Since programs can have many layers of methods written by many different programs, it becomes difficult (impossible) to keep track of which methods might throw exceptions.
Even though Java has the ability to declare exceptions, you can still write a new method with unhandled and undeclared exceptions, and Java will compile it and you can run it and hope for the best. What Java won't let you do is compile your new method if it uses a method that has been declared as throwing exception(s), unless you either handle the declared exception(s) in your method or declare your method as throwing the same exception(s) or if there are multiple exceptions, you can handle some and throw the rest.
When a programmer declares that the method throws a specific type of exception, it is just an automated way of warning other programmers using the method that an exception is possible. The programmer can then decide to handled the exception or pass on the warning by declaring the calling method as also throwing the same exception. Since the compiler has been warned the exception is possible in this new method, it can automatically check if future callers of the new method handle the exception or declare it and enforcing one or the other to happen.
The nice thing about this type of solution is that when the compiler reports Error: Unhandled exception type java.io.IOException it gives the file and line number of the method that was declared to throw the exception. You can then choose to simply pass the buck and declare your method also "throws IOException". This can be done all the way up to main method where it would then cause the program to stop and report the exception to the user. However, it is better to catch the exception and deal with it in a nice way such as explaining to the user what has happened and how to fix it. When a method does catch and handle the exception, it no longer has to declare the exception. The buck stops there so to speak.

Exception is a checked exception class. Therefore, any code that calls a method that declares that it throws Exception must handle or declare it.

package javaexception;
public class JavaException {
void show() throws Exception
{
throw new Exception("my.own.Exception");
}
void show2() throws Exception // Why throws is necessary here ?
{
show();
}
void show3() throws Exception // Why throws is necessary here ?
{
show2();
}
public static void main(String[] args) {
JavaException a = new JavaException();
try{
a.show3();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
Only small changes in your program. What It seems to be misunderstood by many regarding the main issue, is whenever you throw exception you need to handle it, not necessary in the same place ( ex. show1,2,3 method in your program) but you must at first caller method inside the 'main'. in one word, there is 'throw', there must be 'catch/try', even if not same method where exception happens.

void show() throws Exception
{
throw new Exception("my.own.Exception");
}
As there is checked exception in show() method , which is not being handled in that method so we use throws keyword for propagating the Exception.
void show2() throws Exception //Why throws is necessary here ?
{
show();
}
Since you are using the show() method in show2() method and you have propagated the exception atleast you should be handling here. If you are not handling the Exception here , then you are using throws keyword.
So that is the reason for using throws keyword at the method signature.

Basically, if you are not handling the exception in the same place as you are throwing it, then you can use "throws exception" at the definition of the function.

If you propagate the exception by declaring the throws directive in the signature of the current method, then somewhere up the line or call stack a try/catch construct must be used to handle the exception.

Related

Java Exception generates compiler error, but replacing type of exception does not generate a compiler error [duplicate]

Joshua Bloch in "Effective Java" said that
Use checked exceptions for
recoverable conditions and runtime
exceptions for programming errors
(Item 58 in 2nd edition)
Let's see if I understand this correctly.
Here is my understanding of a checked exception:
try{
String userInput = //read in user input
Long id = Long.parseLong(userInput);
}catch(NumberFormatException e){
id = 0; //recover the situation by setting the id to 0
}
1. Is the above considered a checked exception?
2. Is RuntimeException an unchecked exception?
Here is my understanding of an unchecked exception:
try{
File file = new File("my/file/path");
FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){
//3. What should I do here?
//Should I "throw new FileNotFoundException("File not found");"?
//Should I log?
//Or should I System.exit(0);?
}
4. Now, couldn't the above code also be a checked exception? I can try to recover the situation like this? Can I? (Note: my 3rd question is inside the catch above)
try{
String filePath = //read in from user input file path
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){
//Kindly prompt the user an error message
//Somehow ask the user to re-enter the file path.
}
5. Why do people do this?
public void someMethod throws Exception{
}
Why do they let the exception bubble up? Isn't handling the error sooner better? Why bubble up?
6. Should I bubble up the exact exception or mask it using Exception?
Below are my readings
In Java, when should I create a checked exception, and when should it be a runtime exception?
When to choose checked and unchecked exceptions
Many people say that checked exceptions (i.e. these that you should explicitly catch or rethrow) should not be used at all. They were eliminated in C# for example, and most languages don't have them. So you can always throw a subclass of RuntimeException (unchecked exception)
However, I think checked exceptions are useful - they are used when you want to force the user of your API to think how to handle the exceptional situation (if it is recoverable). It's just that checked exceptions are overused in the Java platform, which makes people hate them.
Here's my extended view on the topic.
As for the particular questions:
Is the NumberFormatException consider a checked exception?
No. NumberFormatException is unchecked (= is subclass of RuntimeException). Why? I don't know. (but there should have been a method isValidInteger(..))
Is RuntimeException an unchecked exception?
Yes, exactly.
What should I do here?
It depends on where this code is and what you want to happen. If it is in the UI layer - catch it and show a warning; if it's in the service layer - don't catch it at all - let it bubble. Just don't swallow the exception. If an exception occurs in most of the cases you should choose one of these:
log it and return
rethrow it (declare it to be thrown by the method)
construct a new exception by passing the current one in constructor
Now, couldn't the above code also be a checked exception? I can try to recover the situation like this? Can I?
It could've been. But nothing stops you from catching the unchecked exception as well
Why do people add class Exception in the throws clause?
Most often because people are lazy to consider what to catch and what to rethrow. Throwing Exception is a bad practice and should be avoided.
Alas, there is no single rule to let you determine when to catch, when to rethrow, when to use checked and when to use unchecked exceptions. I agree this causes much confusion and a lot of bad code. The general principle is stated by Bloch (you quoted a part of it). And the general principle is to rethrow an exception to the layer where you can handle it.
Whether something is a "checked exception" has nothing to do with whether you catch it or what you do in the catch block. It's a property of exception classes. Anything that is a subclass of Exception except for RuntimeException and its subclasses is a checked exception.
The Java compiler forces you to either catch checked exceptions or declare them in the method signature. It was supposed to improve program safety, but the majority opinion seems to be that it's not worth the design problems it creates.
Why do they let the exception bubble
up? Isnt handle error the sooner the
better? Why bubble up?
Because that's the entire point of exceptions. Without this possibility, you would not need exceptions. They enable you to handle errors at a level you choose, rather than forcing you to deal with them in low-level methods where they originally occur.
Is the above considered to be a checked exception?
No
The fact that you are handling an exception does not make it a Checked Exception if it is a RuntimeException.
Is RuntimeException an unchecked exception?
Yes
Checked Exceptions are subclasses of java.lang.Exception
Unchecked Exceptions are subclasses of java.lang.RuntimeException
Calls throwing checked exceptions need to be enclosed in a try{} block or handled in a level above in the caller of the method. In that case the current method must declare that it throws said exceptions so that the callers can make appropriate arrangements to handle the exception.
Hope this helps.
Q: should I bubble up the exact
exception or mask it using Exception?
A: Yes this is a very good question and important design consideration. The class Exception is a very general exception class and can be used to wrap internal low level exceptions. You would better create a custom exception and wrap inside it. But, and a big one - Never ever obscure in underlying original root cause. For ex, Don't ever do following -
try {
attemptLogin(userCredentials);
} catch (SQLException sqle) {
throw new LoginFailureException("Cannot login!!"); //<-- Eat away original root cause, thus obscuring underlying problem.
}
Instead do following:
try {
attemptLogin(userCredentials);
} catch (SQLException sqle) {
throw new LoginFailureException(sqle); //<-- Wrap original exception to pass on root cause upstairs!.
}
Eating away original root cause buries the actual cause beyond recovery is a nightmare for production support teams where all they are given access to is application logs and error messages.
Although the latter is a better design but many people don't use it often because developers just fail to pass on the underlying message to caller. So make a firm note: Always pass on the actual exception back whether or not wrapped in any application specific exception.
On try-catching RuntimeExceptions
RuntimeExceptions as a general rule should not be try-catched. They generally signal a programming error and should be left alone. Instead the programmer should check the error condition before invoking some code which might result in a RuntimeException. For ex:
try {
setStatusMessage("Hello Mr. " + userObject.getName() + ", Welcome to my site!);
} catch (NullPointerException npe) {
sendError("Sorry, your userObject was null. Please contact customer care.");
}
This is a bad programming practice. Instead a null-check should have been done like -
if (userObject != null) {
setStatusMessage("Hello Mr. " + userObject.getName() + ", Welome to my site!);
} else {
sendError("Sorry, your userObject was null. Please contact customer care.");
}
But there are times when such error checking is expensive such as number formatting, consider this -
try {
String userAge = (String)request.getParameter("age");
userObject.setAge(Integer.parseInt(strUserAge));
} catch (NumberFormatException npe) {
sendError("Sorry, Age is supposed to be an Integer. Please try again.");
}
Here pre-invocation error checking is not worth the effort because it essentially means to duplicate all the string-to-integer conversion code inside parseInt() method - and is error prone if implemented by a developer. So it is better to just do away with try-catch.
So NullPointerException and NumberFormatException are both RuntimeExceptions, catching a NullPointerException should replaced with a graceful null-check while I recommend catching a NumberFormatException explicitly to avoid possible introduction of error prone code.
1 . If you are unsure about an exception, check the API:
java.lang.Object
extended by java.lang.Throwable
extended by java.lang.Exception
extended by java.lang.RuntimeException //<-NumberFormatException is a RuntimeException
extended by java.lang.IllegalArgumentException
extended by java.lang.NumberFormatException
2 . Yes, and every exception that extends it.
3 . There is no need to catch and throw the same exception. You can show a new File Dialog in this case.
4 . FileNotFoundException is already a checked exception.
5 . If it is expected that the method calling someMethod to catch the exception, the latter can be thrown. It just "passes the ball". An example of it usage would be if you want to throw it in your own private methods, and handle the exception in your public method instead.
A good reading is the Oracle doc itself: http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html
Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope? Any Exception that can be thrown by a method is part of the method's public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method's programming interface as its parameters and return value.
The next question might be: "If it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions too?" Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.
There's also an important bit of information in the Java Language Specification:
The checked exception classes named in the throws clause are part of the contract between the implementor and user of the method or constructor.
The bottom line IMHO is that you can catch any RuntimeException, but you are not required to and, in fact the implementation is not required to maintain the same non-checked exceptions thrown, as those are not part of the contract.
1) No, a NumberFormatException is an unchecked Exception. Even though you caught it (you aren't required to) because it's unchecked. This is because it is a subclass of IllegalArgumentException which is a subclass of RuntimeException.
2) RuntimeException is the root of all unchecked Exceptions. Every subclass of RuntimeException is unchecked. All other Exceptions and Throwable are checked except for Errors ( Which comes under Throwable).
3/4) You could alert the user that they picked a non-existent file and ask for a new one. Or just quit informing the user that they entered something invalid.
5) Throwing and catching 'Exception' is bad practice. But more generally, you might throw other exceptions so the caller can decide how to deal with it. For example, if you wrote a library to handle reading some file input and your method was passed a non-existent file, you have no idea how to handle that. Does the caller want to ask again or quit? So you throw the Exception up the chain back to the caller.
In many cases, an unchecked Exception occurs because the programmer did not verify inputs (in the case of NumberFormatException in your first question). That's why its optional to catch them, because there are more elegant ways to avoid generating those exceptions.
Checked - Prone to happen. Checked in Compile time.
Eg.. FileOperations
UnChecked - Due to Bad data. Checked in Run time.
Eg..
String s = "abc";
Object o = s;
Integer i = (Integer) o;
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at Sample.main(Sample.java:9)
Here exception is due to bad data and in no way it can be determined during compile time.
Runtime Exceptions :
Runtime exceptions are referring to as unchecked exceptions. All other exceptions
are checked exceptions, and they don't derive from java.lang.RuntimeException.
Checked Exceptions :
A checked exception must be caught somewhere in your code. If you invoke a
method that throws a checked exception but you don't catch the checked exception
somewhere, your code will not compile. That's why they're called checked
exceptions : the compiler checks to make sure that they're handled or declared.
A number of the methods in the Java API throw checked exceptions, so you will often write exception handlers to cope with exceptions generated by methods you didn't write.
Checked exceptions are checked at compile time by the JVM and its related to resources(files/db/stream/socket etc). The motive of checked exception is that at compile time if the resources are not available the application should define an alternative behaviour to handle this in the catch/finally block.
Unchecked exceptions are purely programmatic errors, wrong calculation, null data or even failures in business logic can lead to runtime exceptions. Its absolutely fine to handle/catch unchecked exceptions in code.
Explanation taken from http://coder2design.com/java-interview-questions/
My absolute favorite description of the difference between unchecked and checked exceptions is provided by the Java Tutorial trail article, "Unchecked Exceptions - the Controversy" (sorry to get all elementary on this post - but, hey, the basics are sometimes the best):
Here's the bottom line guideline: If a client can reasonably be
expected to recover from an exception, make it a checked exception. If
a client cannot do anything to recover from the exception, make it an
unchecked exception
The heart of "what type of exception to throw" is semantic (to some degree) and the above quote provides and excellent guideline (hence, I am still blown away by the notion that C# got rid of checked exceptions - particularly as Liskov argues for their usefulness).
The rest then becomes logical: to which exceptions does the compiler expect me to respond, explicitly? The ones from which you expect client to recover.
To answer the final question (the others seem thoroughly answered above), "Should I bubble up the exact exception or mask it using Exception?"
I am assuming you mean something like this:
public void myMethod() throws Exception {
// ... something that throws FileNotFoundException ...
}
No, always declare the most precise exception possible, or a list of such. The exceptions you declare your method as capable of throwing are a part of the contract between your method and the caller. Throwing "FileNotFoundException" means that it is possible the file name isn't valid and the file will not be found; the caller will need to handle that intelligently. Throwing Exception means "Hey, sh*t happens. Deal." Which is a very poor API.
In the comments on the first article there are some examples where "throws Exception" is a valid and reasonable declaration, but that's not the case for most "normal" code you will ever write.
I think that checked exceptions are a good reminder for the developer that uses an external library that things can go wrong with the code from that library in exceptional situations.
Why do they let the exception bubble up? Isn't handling the error sooner better? Why bubble up?
For example let say you have some client-server application and client had made a request for some resource that couldn't be find out or for something else error some might have occurred at the server side while processing the user request then it is the duty of the server to tell the client why he couldn't get the thing he requested for,so to achieve that at server side, code is written to throw the exception using throw keyword instead of swallowing or handling it.if server handles it/swallow it, then there will be no chance of intimating to the client that what error had occurred.
Note:To give a clear description of what the error type has occurred we can create our own Exception object and throw it to the client.
I just want to add some reasoning for not using checked exceptions at all. This is not a full answer, but I feel it does answer part of your question, and complements many other answers.
Whenever checked exceptions are involved, there's a throws CheckedException somewhere in a method signature (CheckedException could be any checked exception). A signature does NOT throw an Exception, throwing Exceptions is an aspect of implementation. Interfaces, method signatures, parent classes, all these things should NOT depend on their implementations. The usage of checked Exceptions here (actually the fact that you have to declare the throws in the method signature) is binding your higher-level interfaces with your implementations of these interfaces.
Let me show you an example.
Let's have a nice and clean interface like this
public interface IFoo {
public void foo();
}
Now we can write many implementations of method foo(), like these
public class Foo implements IFoo {
#Override
public void foo() {
System.out.println("I don't throw and exception");
}
}
Class Foo is perfectly fine. Now let's make a first attempt at class Bar
public class Bar implements IFoo {
#Override
public void foo() {
//I'm using InterruptedExcepton because you probably heard about it somewhere. It's a checked exception. Any checked exception will work the same.
throw new InterruptedException();
}
}
This class Bar won't compile. As InterruptedException is a checked exception, you must either capture it (with a try-catch inside method foo()) or declare that you're throwing it (adding throws InterruptedException to the method signature). As I don't want to capture this exception here (I want it to propagate upwards so I can properly deal with it somewhere else), let's alter the signature.
public class Bar implements IFoo {
#Override
public void foo() throws InterruptedException {
throw new InterruptedException();
}
}
This class Bar won't compile either! Bar's method foo() does NOT override IFoo's method foo() since their signatures are different. I could remove the #Override annotation, but I want to program against interface IFoo like IFoo foo; and later on decide on which implementation I want to use, like foo = new Bar();. If Bar's method foo() doesn't override IFoo's method foo, when I do foo.foo(); it won't call Bar's implementation of foo().
To make Bar's public void foo() throws InterruptedException override IFoo's public void foo() I MUST add throws InterruptedException to IFoo's method signature. This, however, will cause problems with my Foo class, since it's foo() method's signature differs from IFoo's method signature. Furthermore, if I added throws InterruptedException to Foo's method foo() I would get another error stating that Foo's method foo() declares that it throws an InterruptedException yet it never throws an InterruptedException.
As you can see (if I did a decent job at explaining this stuff), the fact that I'm throwing a checked exception like InterruptedException is forcing me to tie my interface IFoo to one of it's implementations, which in turn causes havoc on IFoo's other implementations!
This is one big reason why checked exceptions are BAD. In caps.
One solution is to capture the checked exception, wrap it in an unchecked exception and throw the unchecked exception.
Java distinguishes between two categories of exceptions (checked & unchecked).
Java enforces a catch or declared requirement for checked exceptions.
An exception's type determines whether an exception is checked or unchecked.
All exception types that are direct or indirect subclasses of class RuntimeException
are unchecked exception.
All classes that inherit from class Exception but not RuntimeException are considered to be checked exceptions.
Classes that inherit from class Error are considered to be unchecked.
Compiler checks each method call and deceleration to determine whether the
method throws checked exception.
If so the compiler ensures the exception is caught or is declared in a throws clause.
To satisfy the declare part of the catch-or-declare requirement, the method that generates
the exception must provide a throws clause containing the checked-exception.
Exception classes are defined to be checked when they are considered important enough to catch or declare.
Here is a simple rule that can help you decide. It is related to how interfaces are used in Java.
Take your class and imagine designing an interface for it such that the interface describes the functionality of the class but none of the underlying implementation (as an interface should). Pretend perhaps that you might implement the class in another way.
Look at the methods of the interface and consider the exceptions they might throw:
If an exception can be thrown by a method, regardless of the underlying implementation (in other words, it describes the functionality only) then it should probably be a checked exception in the interface.
If an exception is caused by the underlying implementation, it should not be in the interface. Therefore, it must either be an unchecked exception in your class (since unchecked exceptions need not appear in the interface signature), or you must wrap it and rethrow as a checked exception that is part of the interface method.
To decide if you should wrap and rethrow, you should again consider whether it makes sense for a user of the interface to have to handle the exception condition immediately, or the exception is so general that there is nothing you can do about it and it should propagate up the stack. Does the wrapped exception make sense when expressed as functionality of the new interface you are defining or is it just a carrier for a bag of possible error conditions that could also happen to other methods? If the former, it might still be a checked exception, otherwise it should be unchecked.
You should not usually plan to "bubble-up" exceptions (catch and rethrow). Either an exception should be handled by the caller (in which case it is checked) or it should go all the way up to a high level handler (in which case it is easiest if it is unchecked).
Just to point out that if you throw a checked exception in a code and the catch is few levels above, you need to declare the exception in the signature of each method between you and the catch. So, encapsulation is broken because all functions in the path of throw must know about details of that exception.
In short, exceptions which your module or modules above are supposed to handle during runtime are called checked exceptions; others are unchecked exceptions which are either RuntimeException or Error.
In this video, it explains checked and unchecked exceptions in Java:
https://www.youtube.com/watch?v=ue2pOqLaArw
All of those are checked exceptions. Unchecked exceptions are subclasses of RuntimeException. The decision is not how to handle them, it's should your code throw them. If you don't want the compiler telling you that you haven't handled an exception then you use an unchecked (subclass of RuntimeException) exception. Those should be saved for situations that you can't recover from, like out of memory errors and the like.
Checked Exceptions :
The exceptions which are checked by the compiler for smooth execution of the program at runtime are called Checked Exception.
These occur at compile time.
If these are not handled properly, they will give compile time error (Not Exception).
All subclasses of Exception class except RuntimeException are Checked Exception.
Hypothetical Example - Suppose you are leaving your house for the exam, but if you check whether you took your Hall Ticket at home(compile time) then there won't be any problem at Exam Hall(runtime).
Unchecked Exception :
The exceptions which are not checked by the compiler are called Unchecked Exceptions.
These occur at runtime.
If these exceptions are not handled properly, they don’t give compile time error. But the program will be terminated prematurely at runtime.
All subclasses of RunTimeException and Error are unchecked exceptions.
Hypothetical Example - Suppose you are in your exam hall but somehow your school had a fire accident (means at runtime) where you can't do anything at that time but precautions can be made before (compile time).
If anybody cares for yet another proof to dislike checked exceptions, see the first few paragraphs of the popular JSON library:
"Although this is a checked exception, it is rarely recoverable. Most callers should simply wrap this exception in an unchecked exception and rethrow: "
So why in the world would anyone make developers keep checking the exception, if we should "simply wrap it" instead? lol
http://developer.android.com/reference/org/json/JSONException.html
All exceptions must be checked exceptions.
Unchecked exceptions are unrestricted gotos. And unrestricted gotos are considered a bad thing.
Unchecked exceptions break encapsulation. To process them correctly, all the functions in the call tree between the thrower and the catcher must be known to avoid bugs.
Exceptions are errors in the function that throws them but not errors in the function that processes them. The purpose of exceptions is to give the program a second chance by deferring the decision of whether it's an error or not to another context. It's only in the other context can the correct decision be made.

Java main function has to throw exception but who will handle it?

I write a simple program that output "123" into "output.txt". I noticed that if I do not add "throws FileNotFoundException", java could not even compile.
If I do not have throw clause console says Unresolved compilation problem. Unhandled exception type FileNotFoundException on main.
public static void main(String[] args) throws FileNotFoundException{
PrintWriter out = new PrintWrite("output.txt");
out.println("123");
out.close();
}
Why do I have to add throw clause, I tried creating a "output.txt" before building it but problem exists.
Does it mean that main method will throw FileNotFoundException but what is function that will handle it?
The compiler telling you that you need to add a throws declaration just means that you have called a method that (can) throw a checked exception. You could, instead, just catch the exception yourself, so that your method can't throw the exception by leaving it unhandled.
public static void main(String[] args) {
try {
PrintWriter out = new PrintWrite("output.txt");
out.println("123");
out.close();
} catch (FileNotFoundException e) {
// do whatever else
}
}
To address your specific questions:
You have to add a throw clause because if you call a method that throws an exception, and you don't catch it, then your method will throw that exception. Creating the "output.txt" file will not help, because that method still might throw (how do you know that it will exist at runtime just because it's there when you compile?).
If the main method throws an exception, the program will crash.
The FileNotFoundException is a checked exception, meaning that you should define how to handle this exception.
There are 2 ways :
Handle the line with a try-catch block
Declare the method using throws, this means that the caller will
have to handle the exception.
In your example, you've decided to declare the main with throws. It means that on exception your program will terminate.
There are 2 kind of exceptions in Java checked and runtime exceptions. Java language requires developer to handle checked exceptions. If a method can throw checked exception that exception has to be declared with throws keyword in method definition.
Yes, main method will throw this exception. Java language specification 11.3 says that if exception is not handled then thread is terminated. And 12.8 says that program terminates when all non daemon thread terminate. So in this case program will simply exit.
Javadoc for PrintWriter reveals to us that PrintWriter tries to create the file but will fail with FileNotFoundException if file with that name cannot be created. Maybe folder is missing write permission or existing file is locked by some other process, like text editor?
Answering your first question.
In Java, there are two types of exceptions:
1) Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.
Since FileNotFoundException is a subclass of IOException, we can just specify IOException in the throws list and make the above program compiler-error-free.
2) Unchecked: are the exceptions that are not checked at the compiled time. Error and RuntimeException classes are unchecked exceptions
Coming to your second question:
You might think that the public static void main method in Java or the main function in C is the real entry point of your program – but it isn't. All high-level languages (including C) have a language runtime that initializes the program and then transfers control flow to the entry point. In the case of Java, initialization will include:
setting up the JVM
loading required classes
running static initializer blocks.This can execute user-defined code before main is invoked. These blocks aren't supposed to throw exceptions.
There are a variety of ways to implement exception handling, but for the purpose of this question, they all can be viewed as a black box. The important thing however is that the language runtime must always provide an outermost exception handler that catches all exceptions that aren't caught by user code. This exception handler will usually print out a stack trace, shut down the program in an orderly fashion, and exit with an error code. Properly shutting down the program includes destroying the object graph, invoking finalizers, and freeing resources such as memory, file handles, or network connections.

What does "duck an exception" mean?

In the Advantages of Exceptions section of the Java™ tutorials:
A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it.
[...]
...ducking an exception requires some effort on the part of the middleman methods. Any checked exceptions that can be thrown within a method must be specified in its throws clause.
What does "duck an exception" mean here? I searched the web and FOLDOC (Free On-line Dictionary of Computing) but didn't find anything that looked promising.
Well, ducking simply means to lower your head in order to avoid being hit or seen. In this case, 'duck an exception' just means avoiding your code from getting hit by an exception.
For your method not to be hit by exception, you throw it further up the call stack by declaring a throws exception on your method
public void myMethod() throws IOException {
}
If you don't duck, you have to catch it:
public void myMethod() {
try {
// ...
} catch(IOException e) {
// handle exception
}
To "duck an exception" means "not handle the exception". This actually explains the name: to duck means to "To evade; dodge".
The method ducking the exception simply doesn't handle it (because, for example, it is not its purpose) and let the exception be thrown to the calling method.
For example, consider a method whose purpose is to count the number of lines in a file. This would be a simple implementation (Java 8):
private static long numberOfLines(Path path) throws IOException {
try (BufferedReader br = Files.newBufferedReader(path)) {
return br.lines().count();
}
}
Note that this method doesn't handle the IOException that is thrown by Files.newBufferedReader(path), because that's not the method goal. It ducks and let the caller handle it appropriately.
Note the caller might also duck the exception and let its caller handle it, etc.
i think it means a method can catch an exception and re-throw it for other method to catch it and handle it as needed. Or just throw a new exception. Or avoid catching an exception and let it bubble up the call stack. The point is to have a method delegate exception handling to other method which might be more appropriate to handle a given exception (e.g by having access to necessary data and/or state). But (for java) this requires declaring methods with throws clause all the time, which becomes boilerplate easily
as mentioned in #jmcg's comment, literally "DUCK simply means to lower your head in order to avoid being hit or seen" (like ducks do in a river)
I think to duck means re-throw an exception... in other words, ignore it hoping that someone else will handle it :)

Checked and unchecked exception in Java, are these assertions true?

I have some doubts about the difference between checked exception and unchecked exception.
I know that checked exception typically represent invalid conditions in areas outside the immediate control of the program such as invalid user input, database problems, network outages, absent files, etc.
I also know that checked exception are subclass of Exception abstract class and that a method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow).
So, in practice, what exactly means this last assertion?
Can I simply say that checked exceptions are checked at compile-time. It means if a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise the program will give a compilation error. It is named as checked exception because these exceptions are checked at Compile time.
So, if a method throws a checked exception I can handle it in 2 differents way:
I have to handle it into a try-catch block, something like this:
try{
//statements that may cause an exception
} catch (exception(type) e(object))‏ {
//error handling code
}
Using the throws keyword used in method declaration, in order to explicitly specify the exceptions that a particular method might throw. When a method declaration has one or more exceptions defined using throws clause then the method-call must handle all the defined exceptions.
So, correct me if I am sayng a wrong assertion, the throws keyword is used to throw the retrieved checked exception to the upper level in the stack (into the caller). So if a method call another method that throw a checked excepion, if it is thrown the caller method have to handle it (for example by a try catch block). Is it this reasoning correct?
So is it true that checked exceptions have the disadvantage that introduce a form of tight-coupling because if I have a chain of methods and the last one throws a checked exception or I handle it into the code of its father or all the intermediate methods must declare the exception by the throws keyword on the method declaration? Is this assertion correct?
At the contrary the unchecked exception are not checked at compile time. It means if your program is throwing an unchecked exception and even if you didn’t handle/declare that exception, the program won’t give a compilation error. Most of the times these exception occurs due to the bad data provided by user during the user-program interaction. It is up to the programmer to judge the conditions in advance, that can cause such exceptions and handle them appropriately. All Unchecked exceptions are direct sub classes of RuntimeException class.
For example I can have a situation like this:
class Example {
public static void main(String args[])
{
int num1=10;
int num2=0;
/*Since I'm dividing an integer with 0
* it should throw ArithmeticException*/
int res=num1/num2;
System.out.println(res);
}
}
Compiling this class the compiler give me no error but running it I will obtain an ArithmeticException tath is an unchecked exception because it happens at runtime.
So I think that it is the developer that have to handle this case doing something like:
class Example {
public static void main(String args[])
{
int num1=10;
int num2=0;
/*Since I'm dividing an integer with 0
* it should throw ArithmeticException*/
try {
int res=num1/num2;
} catch(ArithmeticException e) {
System.out.println("Division for 0, this is not a good idea !!!");
}
System.out.println(res);
}
}
So my doubts are:
It seems to me that I can use the try catch block also for the unchecked exception. So what is the difference in the use of try catch block that exist between checked exception and unchecked exception? Is it only that with checked exception I have to use it (or use the throws keyword on the method declaration) otherwise I will obtain a compile time error message?
Also the unchecked exception are automatically propagated to the superior level into the stack of the methods call?
Tnx
In regard to the coupling introduced by the throws, you are absolutely right: exceptions declared in the throws clause become part of a method's public interface (in general sense of the word; without regard to Java's interfaces and public access). However, this coupling is not different from that introduced by declaring a return type or parameter types of a method. You can think of it as a third attribute of method's signature.
It seems to me that I can use the try catch block also for the unchecked exception. So what is the difference in the use of try catch block that exist between checked exception and unchecked exception?
You can certainly catch unchecked exceptions, but you should do it at the very top level of your program in order to prevent complete crashes. Unchecked exceptions represent programming errors, so you cannot handle them in a meaningful way. The best you can do is to log them, and move on.
Also the unchecked exception are automatically propagated to the superior level into the stack of the methods call?
Yes, they do so in the same way the checked exceptions do when an exception is declared in the throws clause and not caught.
Yes. You can use try catch block to catch unchecked exceptions as well as checked exceptions.
All exceptions, whether checked or unchecked are propagated up to the next level if not caught.
The difference is that if a method can throw a checked exception E (either because it calls a method that throws E or because it directly throws it itself with the statement throw E) the method declaration must include this information using throws E.
Therefore if you want to call a method that can throw the checked exception E you must either put the method call in a try block or declare throws E. These things are optional for unchecked exceptions.
Most of the time you should not catch an unchecked exception.
There are no differences between try catch of unchecked and checked exceptions. As you told.
-If a method uses another method that may throw a checked exception, one of the two following things should be true:
The method should be enclosed within a try-catch block or The method should specify this exception to be thrown in its method signature.
-A unchecked exception may not be a part of the method signature, even if a
method may throw it.
When a piece of code hits an obstacle in the form of an exceptional condition, it creates an objects of class java.lang.Throwable. Checked and Unchecked Exceptions propagates through method calls because both are subclass java.lang.Throwable.

Can an Error be handled in the same way as an Exception

I want to know whether an error can be handled or not in Java in the similar way to exceptions. I have seen errors that can't be handled such as AssertionError and I've also tried throwing an error inside a program and tried handling using catch, It worked and also the next part of code did execute(This is contradictory to the part where the program supposed to be exited whenever an error is encountered). Is it like few errors can be handled and few others cannot be. I'm confused with this, can anyone clear this doubt of mine and state the difference between errors and exceptions?
package package1;
public class Class1
{
public static void main(String[] args)
{
Class1 cl1=new Class1();
int x=2;
String s = null;
//assert(x<0):"x is not less than zero";
try
{
cl1.workonExceptions();
}
catch (Error e)
{
e.printStackTrace();
}
System.out.println("Not Terminated yet");
}
public void workonExceptions() throws Error
{
try
{
throw new Exception("Exception");
}
catch (Exception e)
{
throw new Error("Exception Again"); }
}
}
Some background on Error: It's not intended to be catchable; it only comes up when something goes really wrong. An exception is meant to be caught and handled, since it's something that may come up on occasion, but shouldn't interrupt or interfere severely with the running of your program, such as dividing by zero.
As for it working inside of a try...catch statement, the reason is that this is a property of the Throwable class.
Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause.
Exceptions, if thrown from a method, are required by the compiler to be caught by callers of that method.
Errors, even if thrown from a method, are not required by the compiler to be caught by callers of the method.
Both Exceptions and Errors CAN be caught by callers, and behave the same way when they are. If you have code that illustrates "continues to execute", I'd be interested in seeing it. If you throw either of these (both derived from Throwable), execution of the method from which they are thrown ceases at that point (absent finally clauses, an (ahem) exception to the rule I'd rather not try to cover in this post).
All errors in Java are catchable, including AssertionError, although it is not recommended to catch them, and it is not guaranteed that the JVM is in consistent enough state to continue execution after an Error. So what you see is completely normal.
Differently from C#, even ThreadDeath is handled pretty much the same as any other Throwable (that is, it can be caught and consumed).
The main difference between errors and exceptions is that methods can throw any errors regardless of their exception specifiers.

Categories

Resources