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.
Related
A simple question and I can't find the answer for it.
Is it required to every exception in Java to use a try-catch? Or is it only for the FileNotFoundException?
A lot of exceptions (IndexOutOfBoundException, ArithmeticException, IlligalArgumentException, NullPointerException) are saying that they didn't need an Exception, but FileNotFoundException does)... and I can't find the answer which do and which doesn't need try-catch.
It's not absolutely required to have a try/catch block for your exceptions. Instead, you can throw them to someone who is able to handle the exception properly.
There are 2 kinds of exceptions: Checked and Unchecked. A Checked exception can be considered one that is found by the compiler, and the compiler knows that it has a chance to occur, so you need to catch or throw it. For example, opening a file. It has a chance to fail, and the compiler knows this, so you're forced to catch or throw the possible IOException.
An Unchecked exception can be considered one that has a chance of occurring, but based on your code, the compiler doesn't know. In other words, it's a programming error. For example, if you're taking user input and expect a number, and the user enters something you didn't expect, such as a string, your program would throw a NumberFormatException. You can predict these scenarios and put try/catch to try and avoid them before they occur. Very rarely seen is a person adding a throws NullPointerException or throws NumberFormatException (or throwing any other Unchecked exception, for that matter). It's allowed, but explicitly creating that exception is weird and most people would say that it's bad coding style.
Note that all Checked suggestions must be caught or thrown to something that can handle it; if you don't do it, your program won't compile. If you throw it to something that can't handle it, then your program will likely crash if it occurs.
Also note that an unchecked Exception (eg: one that occurs during runtime, usually via bad user input or whatnot) will also usually crash your program. Thus, it's usually a good idea to use try/catch when something can potentially go wrong, but you don't have to.
Also interesting to note is that while Checked exceptions are subclasses of Exception and Unchecked exceptions are subclasses of RuntimeException, RuntimeException itself is a subclass of Exception. That means that if you really wanted to, a single try {} catch (Exception e) {} will catch every single exception your program could possibly throw. Granted, this is considered a horrible way to deal with exceptions, and you should catch each one separately so that you can handle them separately. Please try not to use it.
No, not every exception requires a try-catch. Every checked exception requires a try catch. For example, a NullPointerException is an unchecked exception, so it does not require a try-catch, whereas a FileNotFoundException is checked, so it does require one. You can also add "throws" to the method signature and thus avoid needing a try-catch.
Read:
https://docs.oracle.com/javase/tutorial/essential/exceptions/
Basically checked Exceptions need to be handled or thrown
Unchecked Exceptions and Errors may be handled or thrown (although handling Error is in general considered bad practise).
Checked exception is everything that inherits from java.lang.Exception
Unchecked exception is everything that inherits from java.lang.RuntimeException
Error is everything that inherits from java.lang.Error
Only Checked exception explicit need to catch it, for other all kind of exception you can use "throws" to the method signature.
Yes, but if you don't want to handle it in your method you can pass the exception to the caller of the method with the throws keyword. Example:
void execption() throws Exception {
throw new Exception();
}
void caller() {
try {
execption();
} catch (Exception e) {
e.printStackTrace();
}
}
Edit: I'm a bit rusty on my java, like josh said you can have unchecked exceptions that don't need a try/catch like NullPointerException, but you can add one if you think an unchecked exception may be thrown. Example:
Object obj = null;
obj.hashCode();// if you think a NPE will be thrown you can use a try/catch here
When a method that you call explicitly throws an exception then you have to use try....catch loop. But in case of the list you have given are all runtime exceptions. They get thrown when sometimes a program has inputs that were not expected or the program was put to some use that it was not intended for. These would not require a try....catch loop.
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.
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.
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.
when declaring a methods with "IllegalAccessException" eclipse forces me to
declare the method as throwing an exception
public void a() throws IllegalAccessException {
if(x == 1){
throw new IllegalAccessException("TEST);
}
}
and in method b that uses "IllegalStateException" i dont need to declare the method as throw an exception
public void b() {
if(x == 1){
throw new IllegalStateException("TEST);
}
}
what is the different between thous exception
that one forces me tho declare the method that throw an exception
and the other is not
thank you
Because IllegalAccessException is not RuntimeException (i.e. is checked exception) and IllegalStateException is a RuntimeException (i.e. is unchecked exception).
Read this for more information: Difference between java.lang.RuntimeException and java.lang.Exception
And this explanation on Oracle site: http://download.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html
The first kind of exception is the checked exception. These are exceptional conditions that a well-written application should anticipate and recover from. For example, suppose an application prompts a user for an input file name, then opens the file by passing the name to the constructor for java.io.FileReader. Normally, the user provides the name of an existing, readable file, so the construction of the FileReader object succeeds, and the execution of the application proceeds normally. But sometimes the user supplies the name of a nonexistent file, and the constructor throws java.io.FileNotFoundException. A well-written program will catch this exception and notify the user of the mistake, possibly prompting for a corrected file name.
Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.
The second kind of exception is the error. These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. For example, suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. The unsuccessful read will throw java.io.IOError. An application might choose to catch this exception, in order to notify the user of the problem — but it also might make sense for the program to print a stack trace and exit.
Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses.
The third kind of exception is the runtime exception. These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These usually indicate programming bugs, such as logic errors or improper use of an API. For example, consider the application described previously that passes a file name to the constructor for FileReader. If a logic error causes a null to be passed to the constructor, the constructor will throw NullPointerException. The application can catch this exception, but it probably makes more sense to eliminate the bug that caused the exception to occur.
Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime exceptions are those indicated by RuntimeException and its subclasses.
IllegalAccessException is a checked exception. Checked exceptions must be declared or handled as they are expected results of an operation.
IllegalStateException is an unchecked exception. Unchecked exception are generally considered programming errors and it is not expected to receive one as part of normal program execution. When a programming error does occur, these exceptions are printed to standard error by default with a stack trace so the developer can determine what the programming error was.
As you can see in the Javadoc of the JDK, the IllegalStateException is a RuntimeException, which is not the case of the IllegalAccessException.
And as stated by this Javadoc:
RuntimeException is the superclass of
those exceptions that can be thrown
during the normal operation of the
Java Virtual Machine.
A method is not required to declare in
its throws clause any subclasses of
RuntimeException that might be thrown
during the execution of the method but
not caught.
That explains the difference.
It's part of the Java design that some exceptions need 'throw' declarations and some don't. Those that don't are called 'run time exceptions' and descend from "RuntimException". IllegalAccessException is not a runtime exception, and IllegalStateException is.
The logic behind the difference is that general exceptions are intended for exceptional cases that might occur at any time, no matter what the programmer does, and should always be handled by the programmer if they want their code to be rebust. An IllegalAccessException, or an IO Excection, might be caused by a failure of hardware, or access permissions, which are outside the programmers control. The software needs to do something when they occur, and having a throws clause forces the programmer to think about what to do. IllegalStateException is a symptom of a programmer error of some kind, and so doesn't necessarily need to be handled.