Why I need to put the throws clause in the main method to handle the exception? It shouldn't be only the try-catch supposed to handle exceptions? Sorry for my english
public static void main(String[] args) throws IOException {
createFileDude();
}
public static void createFileDude() throws IOException {
File file = new File("C:\\Users\\User\\Desktop\\Test.txt");
try {
System.out.println("Create file>> " + file.createNewFile());
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
Exception means something went wrong in the 'current method'. Now, the developer can handle it in the catch block of current method, or just tell to the calling method that something went wrong for them to handle.
Like this, eventually the developer can cascade the error back to the operating system. So, it is all about throwing the error back to the calling method or not throwing it back at some point.
In this case, there are two places where you as a developer can decide if the exception message be cascaded back to the OS or not, first is in the method you wrote. As I see you wrote that the exception be thrown, now in main method, you as a developer again have a chance to not throw it to OS (by enclosing in it try-catch but don't throw in catch block), or throw it to OS.
In your example you chose to throw it back to the OS by adding throws clause.
From Java perspective, Java wants the you (the developer) make a conscious decision on any given (checked) exception, and so you'll see compilation errors until you either suppress the exception by not throwing in, or until you actually throw it back to the OS from the 'main' method.
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.
Okay, so I have a bunch of exception related questions across SO and Programmers, but there's just so much to ask, and either I don't know what to type, or not that many people have asked.
So, let's say I have a method that throws a FileNotFoundException (FNFE). I then have another method that uses the first one, but also throws a IOException (IOE).
My handler would catch both and do different things with each, but my IDE (IntelliJ) is signaling I have "a more general exception, 'java.io.IOException', in the throws list already".
I know it works if I do this:
public File openOrCreate(String pathStr) throws FileNotFoundException,
IOException {
try {
// Method that generates the FNFE
Path path = ReposioryProposition.getPath(pathStr);
File file = path.toFile();
catch (FileNotFoundException fnfe) {
throw fnfe;
}
if (!file.exists())
file.createNewFile(); // IOE
return file;
}
But do I need to do it explicitly? Will it work without, or more dangerously, will sometimes work without the explicit version.
To make sure we are on the same page, this is how I initially wrote the thing:
public File openOrCreate(String pathStr) throws FileNotFoundException,
IOException {
Path path = ReposioryProposition.getPath(pathStr);
File file = path.toFile();
if (!file.exists())
file.createNewFile();
return file;
}
But I am unsure what happens, is the FNFE thrown or swallowed up ? My intention is to catch them separately and do different stuff for one over the other.
You only have to include the more general exception in your throws list. This already specifies that the method may throw any subclass of this exception.
In particular, you must handle the more general exception anyway, and this exception handler will also handle the subclass. If you want to handle the subclass explicitly, you have to catch it before the more general exception:
try {
...
}
catch (FileNotFoundException e) {
// handle subclass
}
catch (IOException e) {
// handle general exception (this will not be executed if the
// exception is actually a FileNotFoundException
}
It's perfectly fine to omit the FileNotFoundException from the throws clause if you already have IOException in it.
Doing so doesn't affect the behaviour at all. FileNotFoundException will still be thrown, and you can catch it explicitly (as well as also having a different, more general, catch of IOException).
Having IOException in the throws clause simply states that IOException or any of its subclasses will be thrown from this method. FileNotFoundException is included in that.
Here is what Java Language Specification has to say:
If the run-time type of V is assignment compatible with (ยง5.2) a
catchable exception class of any catch clause of the try statement,
then the first (leftmost) such catch clause is selected. The value V
is assigned to the parameter of the selected catch clause, and the
Block of that catch clause is executed, and then there is a choice:
...
(Emphasis and ellipsis mine).
Therefore, if you want your more specific catch clause to be executed, you have to place it first in the catch list.
But do I need to do it explicitly? Will it work without, or more dangerously, will sometimes work without the explicit version.
Yes. You have to do it explicitly, because it is a checked exception.
Directly throwing back the exception:
If you just add those checked exception to your methods signature, meaning if you add throws clause in method heading like throws IOException, then you need not to catch anywhere in your method.
But doing this has one flaw, If you are accessing n files line by line in your code and each line may throw IOException, if the exception is raised. You must close the file .close() before throwing it back to the called method. So using only this throws clause will not let you to do it.
So, just catch the exception and do necessary action either in catch or finally block.
Only if no action is needed from your side and also if you want the exception to be popped out to the called method and the called method handles it, only then add the throws signature to the method.
you can catch first the sub class exception if not, then the general exception class like this
try{
// something
} catch(FileNotFoundException fne){
// Handle the exception here
} catch(IOException ioe) {
// Handle the IOException here
}
I am creating a basic math parser with Java and doing this is revealing my shallow understanding of Java exception handling.
when I have this input:
String mathExpression = "(3+5";
and I subsequently call:
throw new MissingRightParenException();
the IDE forces me to surround with a try/catch like so:
try {
throw new MissingRightParenException();
} catch (MissingRightParenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
however, in order to force this to be a fatal exception, it looks like I have to add my own code to call System.exit(), like so:
try {
throw new MissingRightParenException();
} catch (MissingRightParenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(0);
}
I am not sure I understand the syntax behind all of this, especially why I have to use a try/catch block around throwing an exception.
what is the rhyme and reason behind this?
Instead of throwing the exception, I could do this instead:
new MissingRightParenException();
instead of calling
throw new MissingRightParenException();
so I guess my question is - if this is a fatal exception, what is the best way to make it truly fatal while giving the user the best feedback?
If you want to have a checked exception that you have to catch - but not right away - then you can define throws MissingRightParenException in the signature of your methods.
class MissingRightParenException extends CalculationException {
...
}
class CalculationException extends Exception {
...
}
class MyClass {
int myMathRelatedMethod(String calculation) throws CalculationException {
...
if (somethingWrong) {
throw new MissingRightParenException("Missing right paren for left paren at location: " + location);
}
...
}
public static void main(String ... args) {
...
try {
myMathRelatedMethod(args[0]);
} catch (CalculationException e) {
// stack trace not needed maybe
System.err.println(e.getMessage());
}
...
}
}
You can also define it as the cause of a RuntimeException but that doesn't seem a good match for your current problem.
try {
...
throw new MissingRightParenException();
...
} catch (MissingRightParenException e) {
// IllegalStateException extends (IS_A) RuntimeException
throw new IllegalStateException("This should never happen", e);
}
If your MissingRightParenException class extends RuntimeException then you don't have to catch it. The message will fall through all methods where it (or it's parent classes such as Throwable, Exception and RuntimeException) is not explicitly caught. You should however not use RuntimeExceptions for input related errors.
Usually the user will get the stack trace or at least the error message, although that depends of course or the error handling further down the line. Note that even main does not have to handle exceptions. You can just specify throws Exception for the main method to let the console receive the stack traces.
So in the end: use throws in the signature of your methods instead of catching exceptions before you want to handle them.
Assuming that your exception is currently a subclass of Exception, which is a Checked Exception, you need to handle in a try catch. If you can make your exception a RunTimeException, you no longer need to do the try-catch stuffs.
what is the best way to make it truly fatal while giving the user the
best feedback?
Personally, I don't think a missing parenthesis should be a Fatal exception. The user should have the possibility to re-try.
However, if you really want to know, It is not possible with java to create a custom fatal exception as fatal exception means something went wrong on the system/jvm, not on the program itself. Still, you should change System.exit(0) to System.exit(1) or anything not equal to 0 as a program exiting with 0 as error code mean everything went right which is not the definition of an exception.
I am not sure I understand the syntax behind all of this
Basically what you do here is throw an exception so you have two choices, either catch it or re-throw it but anyway it will have to be caught somewhere. Then in the catch you simply end the program returning an error code meaning that something failed System.exit(1)
See this Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java for a better understanding of error code.
If MissingRightParenException is a checked exception (that seems to be the case, otherwise your IDE wouldn't be "nagging") then either you have to wrap it inside a try ... catch block or declare it via a throws clause in the method definition. The latter allows you to "bubble up" the exception and catch in the caller of your method throwing the MissingRightParenException exception.
Did you think about a throws clause?
I have written a music player in Java, but I have a problem with finding an exception to throw. Basically, what I want the exception handler to throw is if a filename of a song stored in the playlist is altered or if the file is deleted, as naturally, in that case it won't play. I first thought it was an IOException I would need, but it gave me the error saying
exception IOException is never thrown in body of corresponding try statement
Now, I understand that that means that I'm working with the wrong Exception class, and so I tried to write my own that extends Exception, but it gives me the same error when I try to compile. Can anyone see what I'm doing wrong?
This is the method as it is right now:
public void play() throws NoMatchException
{
if(player != null) {
player.stop();
}
try{
int fileToPlay = tracklist.getSelectedIndex();
String filename = organizer.getFile(fileToPlay);
Media song = new Media(filename);
player = new MediaPlayer(song);
setVolume(currentVolume);
player.play();
player.setOnEndOfMedia(new Runnable() {
#Override public void run() { next(); }
});
}
catch (NoMatchException e){
//Some exception
}
}
When you are not sure what exception you need to catch, go to the documentation of the corresponding method. It turns out that the constructor of Media would throw MediaException - this is the exception that you need to catch. Scroll down to the "throws" section, and look for the exceptions that do not extend RuntimeException (runtime exceptions usually indicate programming errors; the need to catch this is rare).
When you are deciding to catch an exception at a particular level of your program, see if your code can do something meaningful about it. You shouldn't be catching exceptions unless you know what to do when to catch them.
This code makes no sense.
Your catch block is empty and does nothing. Your method says it throws a NoMatchException. Why don't you eliminate the try/catch and let it do so?
You catch exceptions when you have a viable strategy for recovering. Doing nothing is not a strategy. Just let it bubble up and let the caller deal with it.
If you do have a viable recovery strategy, implement it in the catch block and remove the throws clause from the method signature. Either one or the other, but not both.
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.