When we write this ->void add() throws ArithmeticException. It indicated methos add may or may not throw an ArithmeticException. so the calling method has to write try and catch block in order to handle this exceprtion. Then what does it mean when we write this -> public static void main(String[] args) throws IOException. even if main method throws IOException there is no calling methosd to handle it. so what does it mean when we write main methos throws an exception?
Because IOException is a checked Exception and main is just a method like any other, than if a checked Exception is thrown in a method, it has to be declared in the method signature. In other words, main might be the entry point, but it could also be called like any method, and even as an entry point it's called by other code in the JVM.
The main method is not really any different from any other method. It is only special because it is defined as the entry point of your application. In the event that it throws an exception, and there is no handler, your program will crash and cease to function. However, there are scenarios where the main method can be handled. For example:
public class a{
public static void main(String[] args)throws IOException{
throw IOException;
}
}
//some other class:
String[] args = {};
new a().main(args);
what does it mean -> public static void main(String[] args) throws
IOException
it means, the main method is not catching any exceptions, instead it handles the IOException by throwing it to the source which invoked the main method.
You throw Exception if you want it to be handled by higher function or calling function.
remember, when you throw Exception The exception doesn't just disappear, It stil has to be handled by calling function. otherwise it'll crash the program.
Example :
public void iThrowException() throws Exception{
throw new Exception("It has to be handled!");
}
whenever you want to call this method you should call inside try/catch block
like this
public void iWillHandleIt(){
try{
iThrowException();
}catch(Exception e){
System.err.println("Exception caught: "+e);
}
}
As in your case if you throw Exception from main method, caller of main() method i.e.; JVM need to handle the exception. otherwise it will lead to crash.
you'll get better idea if you go throw Read more about Checked and UncheckedExceptions here
public static void main(String[] Args) throws IOException
{
......
}
where this specifies that the method may going to throws IOException and insist the compiler that the block which is calling this method needs some special attention towards this regarding handling or again throwing back.
throws IOException: the logic present within the main method performs some I/O related tasks, and to make sure that the program does not crash owing to some I/O related issues, this work as a fail- safe. Alternately, wrapping the responsible code within a try- catch construct also works.
Related
This question already has answers here:
Difference between throw and throws in Java? [duplicate]
(3 answers)
Closed 3 years ago.
I saw a video that explains throws and throw as follows:
Throws - is used to delegate/pass on the exception to the caller method.
class test{
void child() throws filenotfoundException{
//////## this method passes the exception to its caller which is main method
File f = new File("abc")
}
public static void main(String[] args) throws filenotfoundException{
//////##this main method passes the exception to its caller which is JVM
}
}
So in the above example, if file 'abc' doesn't exist, and the exception is not handled using try catch in the child method, the child method will pass on the exception to main method.
As the main method doesn't handle the exceptions using try catch, it also throws or passes the exception to its caller method which is JVM.
Is it correct?
Throw - JVM only understands the logic to pick up predefined exceptions. And hence all the user defined exceptions should manually be created using new Exception and then passed on to JVM using throw keyword.
is it right as well?
The explanation is flawed. First, child() as written isn't going to throw a thing. File not found is not an exception so far and wouldn't be unless you tried to open the file for input.
From your code, though, child() could possibly throw the exception, as could main(). Child doesn't, but it's defined that it might.
Throw is how you actually, well, throw the exception. Like this:
void child() throws FileNotFoundException {
File f("garbage");
if (!f.exists()) {
throw new FileNotFoundException("the world is clean as garbage does not exist");
}
}
Your main() doesn't have a try/catch block, but it could:
void main() {
try {
child();
}
catch (FileNotFoundException e) {
// Oh no!
}
}
throws is used in the method signature to tell everyone that "yes, this method throws an Exception of X type, please be wary" while throw is used to actually launch this Exception and abort the execution of the function.
Yes, depending on the exception, and if you catch it or not, it might bubble all the way up to the JVM. Some Exceptions do not cause the execution to abort however. These are known as RuntimeExceptions. The programmer can decide to handle them, or not, using a try/catch block. RuntimeExceptions do not need to be declared in the function signature.
My question is when we use "throws" methodology to throw an exception, why we need to give it in front of main method inspite of already thrown it in respective method which required that like add() method will throw the exception if am using Inputstream reader to take the input, so i used "throws IOException" in front of it and executed the code. But error was coming to handle the IOexception in main thread. So, when i appended "throws IOException" in front of main thread, it executed fine. But i did not get why error was coming in main thread part as add() method was the one to generate the exception and there i handled it.
Please explain this. :)
Code:
class A {
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
public void add() throws IOException {
int a=Integer.parseInt(br.readLine());
int b=Integer.parseInt(br.readLine());
System.out.println("Value after addition : "+(a+b));
}
public static void main(String args[]) throws IOException {
A a=new A(); a.add();
}
}
But i did not get why error was coming in main thread part as add() method was the one to generate the exception and there i handled it.
No, you didn't handle it there. You let it propagate up to the calling method.
Handling an exception means catching it and doing something appropriate:
public static void main(String args[]) {
A a=new A();
try {
a.add();
} catch (IOException e) {
// Don't really know how you want to handle it, so I'll just print a line on System.err.
System.err.println("add() failed!");
}
}
When you use "throws" you don't treat your exception. you just say that you don't want to treat it there and you will treat it in other place (the place you call the method).So throwing it from the method means that you have to treat it from the main or any other place you call your method
interface AutoClosable has following method declaration:
void close() throws Exception
Thus we see that method close can throws Exception.
When I write code try-with resources it is looks like this:
private static void printFileJava7() throws IOException {
try(FileInputStream input = new FileInputStream("file.txt")) {
int data = input.read();
while(data != -1){
System.out.print((char) data);
data = input.read();
}
}
}
At this code is absent Exception handling.
I don't understand what happens if close method throws exception.
Java catches and suppresses exceptions thrown by the close method in a try-with-resources block.
You can read more about this here, see in particular the paragraph after the second code sample. http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
You are right that close() method defined in AutoClosable throws exception. However other interface named Closable that extends AutoClosable redefines this method as following:
void close() throws IOException
All IO related classes implement Closable, so their close() method throws IOException. But your method throws it too, so in your code no-one catches this exception. As always it will be caught by upper layer of your application or by JVM itself if no-one catches it before.
From the jls about Compile-Time Checking of Exceptions
When interfaces are involved, more than one method declaration may be overridden by a single overriding declaration. In this case, the overriding declaration must have a throws clause that is compatible with all the overridden declarations (ยง9.4.1).
So when you have something like
static class AC implements AutoCloseable {
#Override
public void close() throws Exception {
throw new Exception("btooom!");
}
public void ac() {
System.out.println("no");
}
}
public static void main(String[] args) throws Exception {
try(AC ac = new AC()) {
ac.ac();
}
}
then you are forded to either add a catch clause to the surrounding try block or add a throws declaration.
In the case of FileInputStream and to apply what the jsl states, the AutoCloseable's close method is overriden from Closeable's, hence you only have to catch an IOException or add it to throws clause.
Further the javadocs of AutoCloseable#close states
While this interface method is declared to throw Exception, implementers are strongly encouraged to declare concrete implementations of the close method to throw more specific exceptions, or to throw no exception at all if the close operation cannot fail.
The key to this particular scenario is the "supressed exception".
"Whenever an exception is thrown within the body, and then followed
by an exception thrown by the try-with-resources statement, only the
exception thrown in the body of the try is eligible to be caught by
the exception handling code. All other exceptions are considered supressed exceptions"
A concept that is new with Java 7.SO you will get the same output as when only the printfileJava7 class throws an exception, since the CloseException thrown by the close() method would be suppressed.
Please refer to When two exceptions are thrown by the try-with-resources construct link.Which have taken exact scenario what You have asked
You need to have a catch block followed by try in the method printFileJava7(). If you don't want to catch it here, you need handle it in the method which calls the method printFileJava7(). We have to catch in one of the layers otherwise it will be propagated back to the calling client.
I'm reviewing a midterm I did in preparation for my final exam tomorrow morning. I got this question wrong, but there's no correct answer pointed out, and I neglected to ask the prof about it.
Consider the following code snippet:
public static void main(String[] args) throws FileNotFoundException
Which of the following statements about this code is correct?
The main method is designed to catch and handle all types of exceptions.
The main method is designed to catch and handle the FileNotFoundException.
The main method should simply terminate if the FileNotFoundException occurs.
The main method should simply terminate if any exception occurs.
I had chosen the second option.
Answer is number 4,
4.- The main method should simply terminate if any exception occurs.
The throws clause only states that the method throws a checked FileNotFoundException and the calling method should catch or rethrow it. If a non-checked exception is thrown (and not catch) in the main method, it will also terminate.
Check this test:
public class ExceptionThrownTest {
#Test
public void testingExceptions() {
try {
ExceptionThrownTest.main(new String[] {});
} catch (Throwable e) {
assertTrue(e instanceof RuntimeException);
}
}
public static void main(String[] args) throws FileNotFoundException {
dangerousMethod();
// Won't be executed because RuntimeException thrown
unreachableMethod();
}
private static void dangerousMethod() {
throw new RuntimeException();
}
private static void unreachableMethod() {
System.out.println("Won't execute");
}
}
As you can see, if I throw a RuntimeException the method will terminate even if the exception thrown is not a FileNotFoundException
Dude, a little late, but answer is Number 3.
Number 1 is false because it is not handling FileNotFoundException
Number 2 is false for the same reason.
Number 3 is true. If a FileNotFoundException is thrown, the main method will terminate.
Number 4 is false. It would not terminate in case of ANY exception. It would terminate only in case of unchecked exception or FileNotFoundException. If there are not other checked exceptions declared in the 'throws' clause, it means they are being handled within the method.
The main method is not catching any exceptions, instead it handles the FileNotFoundException by throwing it to the source which invoked the main method.
The system runtime launches the JVM classes, one specific class among the JVM classes invokes the main method.
The handling for the main method's throws is at the mercy of the JVM classes in that case.
You can read about it in the Java language specification provided by Oracle.
Additionally you can view the source code for some of the JVMs available out there, going that path though takes you away to other programming languages,OpenJdk.
I thought of sharing my small humbled research crust in that topic, hope it helps curious ones :)
I agree with some other answers that the correct answer to the question is option 3. Option 4 says:
The main method should simply terminate if any exception occurs.
Note the "any" in this option. Here's an example of code in which an exception occurs, but main() does not terminate:
public static void main(String[] args) throws FileNotFoundException {
try {
methodThatThrowsACheckedException();
} catch (SomeCheckedException e) {
// do something to handle this exception
}
}
In this code an exception occurs, but the method does not terminate, as it's been setup to handle this exception. If the exception were an uncaught UncheckedException, then the method would terminate, of course. The point of option 4, though, is that any counter-example invalidates it, since it says "any" exception occurs.
Option 3, however, limits this termination to only occur when the exception in the method's signature is thrown:
The main method should simply terminate if the FileNotFoundException occurs.
The reason option 3 makes more sense is because code like the following does not make sense in practice:
public static void main(String[] args) throws FileNotFoundException {
try {
methodThatThrowsFileNotFoundException();
} catch (FileNotFoundException e) {
// do something to handle this exception
}
}
It doesn't make much sense to declare that a method throws an exception, but catch that exception in the method (unless, perhaps, you re-throw it after doing something, in which case option 3 still holds, as the method terminates eventually).
With only the declaration of main(), it is impossible to say which answer is objectively correct. Any of the statements could be true, depending on the definition of the method.
The main method is designed to catch and handle all types of exceptions.
The main method is designed to catch and handle the FileNotFoundException.
Both of the above statements are true of the following:
public static void main(String[] args) throws FileNotFoundException {
while (true) {
try {
doSomething();
}
catch (Exception e) {}
}
}
The declared exception is never thrown by main(), but that is not an error; just pointless and misleading.
The main method should simply terminate if the FileNotFoundException occurs.
The main method should simply terminate if any exception occurs.
Both of the above statements are true of the following:
public static void main(String[] args) throws FileNotFoundException {
try {
doSomething();
}
catch (Exception e) {
return;
}
}
Of course, we can guess at the intention of the question based on what a decent and reasonable programmer might intend to communicate with this method signature. Which would be that they intend for the method to throw FileNotFoundException, and necessarily handle other checked Exceptions. We can also reasonably assume that "handle" does not just mean "process", but specifically that it will not (re-)throw such an exception.
These assumptions immediately rule out #1 and #2.
The remaining question is whether "simply terminate" includes throwing an exception, or only an explicit return/System.exit(). In the former case, both of #3 and #4 could still be true:
public static void main(String[] args) throws FileNotFoundException {
try {
doSomething();
}
catch (FileNotFoundException fnfe) {
throw fnfe;
}
catch (Exception e) {
return;
}
}
In the latter case, neither #3 nor #4 can be true while also satisfying the assumption that main() will throw FileNotFoundException.
In sum, the options are not worded well. If I had to pick an answer, it would be #3 based on the logic of MartinV's answer. My assumption would be that the word "should" in #3 was an unfortunate choice by the professor, and that something like "may" would have been a better option. It would also have been a good idea to use more precise language than "simply terminate" (and, arguably, "handle").
The answer is both 2 & 3.
2.The main method is designed to catch and handle the FileNotFoundException.
3.The main method should simply terminate if the FileNotFoundException occurs.
But if fails to handle the exception even though it is designed to handle it and the programs gets terminated abnormally.
throws keywords is used to make JVM handle the exceptions which we are lazy to handle, it compiles successfully but shows the exception during runtime(if u handle it in main method then it compiles and runs successfully).
4.The main method should simply terminate if any exception occurs.
Is not correct always because the exceptions which occurs may be handle in the main method.
1.The main method is designed to catch and handle all types of exceptions.Is incorrect as JVM doesn't handle unchecked exceptions.
When a method throws and exception, do we need to have a try block inside the method?
For example,
public void foo() throws SomeException{
try{
// content of method
}
}
Is the try block required? Or, is the method able to throw a SomeException without it :
public void foo() throws SomeException{
// content of method
}
This is the case when we are not explicitly throwing a SomeException with throw.
If SomeException is a checked exception you have to either
Use a try{}catch block or
Declare that your method throws it.
You do not have to do both, either example you show in your question works just fine.
The difference is that with the try clause you handle the SomeException yourself, whereas by declaring that your own method throws it you delegate the responsability of handling the SomeException to the calling method.
When a method throws an exception it passes responsibility to handle exception to its caller.
So you don't need to handle exception if you throw it in your signature. Like as follows.
public void foo(){
try{
// content of method
}
}
but if you write it this way.
public void foo() throws SomeException{
}
you will call your method like as follows.
try{
foo();
}
You don't need a try block.
public void foo() throws SomeException {
// do some stuff
// you decide to throw the exception by yourself:
if (throwAnException) throw new SomeException();
// or you call a method that throws SomeExpection:
methodThatCanThrowSomeException();
// do more stuff
}
As long as you declare it in your signature, you're prefectly fine. The caller of your method has to handle the exception, not you. So a caller might do:
try {
foo();
} catch (SomeException e) {
// handle exception
}
Or he might pass it further along by himself.
The most problematic case you'll regularly encounter is calling a method that declares a checked exception. In the great majority of real-life cases it is not appropriate to handle that exception at the spot, but let it propagate upwards. Unfortunately, Java makes you redeclare this same exception all the way up, which creates clutter, exposes implementation details, and often also breaks the contracts of existing methods.
In such a case the way to proceed is to wrap and rethrow:
catch (RuntimeException e) {throw e;} catch (Exception e) {throw new RuntimeException(e);}
1. If the method that we are calling from a program throws an Exception, then we need to usetry/catch around the method invocation.
2. Suppose we are writing a method that throws an exception, then we need to throw new Exception object from withing the method.
3. An exception is an object of type Exception. We have Checked Exception, and Unchecked Exception (Runtime Exception).
you don't essentially need to have a try block in it
public void foo() throws SomeException {
// do some stuff
// you decide to throw the exception by yourself:
if (throwAnException) throw new SomeException();
// or you call a method that throws SomeExpection:
methodThatCanThrowSomeException();
// do more stuff
}