Public static void main string args throws ioexception in java

Java: Is it possible to throws IOException once and for all?

I am new to Java. And I find it really annoying to keep writing throws IOException in the «main» and all the methods that open a file. For example:

class something < public static void main(String[] args) throws IOException< myobj abc = new myobj(); abc.read_file("this_file.txt"); abc.insert("text"); >> class myobj < . public void read_file(String file_loc) throws IOException< blablabla >> 

In this case, I have already written «throws IOException» twice. Is there a way to handle this once and for all ? Edit: Thanks for all the good answers. A lot of people suggested using try-catch statements. I read about try and catch statements and I got really confused. My question is where should I carry on writing my code i.e. abc.insert(«text») into the try catch statements after abc.read_file(«this_file.txt») ? Should I carry on in catch block or outside it ? This is what really puzzles me.

Yes, I understand that it can seems boring. but it is very very important. After some time passed over Java more complex works. you will appreciate the Java exception management. 😉

It is, well without a NullPointerException there’s no java. You’ll see that a lot this one learning this language. 🙂

5 Answers 5

There’s no catch-all «all methods in this class throw this exception,» you’ll have to declare the exception on each method (e.g., read_file , etc.) or handle it within the method. This is the point of checked exceptions: To ensure that at each stage, it’s clear where they may come from and where they’re handled.

Note: main shouldn’t throw, you should catch the exception and handle it.

Who is main throwing to? No one.

Java has checked and unchecked exceptions. Checked exceptions leave you no choice: you either have to catch them or add them to your method signature in a throws clause.

Unchecked exceptions don’t require handling.

You always have the option of catching a checked exception and rethrowing it as a custom unchecked exception.

class something < public static void main(String[] args) try < myobj abc = new myobj(); abc.read_file("this_file.txt"); >catch (IOException e) < e.printStackTrace(); >> > class myobj < . public void read_file(String file_loc) throws IOException< blablabla >> 

But this is just what the default exception handler will do anyway so what is the advantage of this? Personally, I’m getting very suspect if I see catch — printStackTrace constructs as they are a common symptom of “getting rid” of exceptions, rather than dealing with them properly. Unfortunately, a popular IDE encourages this idiom by its default code generation.

I typically do a different approach and I make main declare it’s checked exceptions. Then, I do any necessary clean-ups in a try/finally, letting the exception bubble up. The reason for this is that sometimes (be it for testing or integration) other code might invoke another class’s main with pseudo-CLI arguments computed programmatically or declaratively or what not. Unless I have a really good reason, I never expect my main functions to be called exclusively from the command line.

What does «dealing with them properly» look like, especially in this contrived, simplistic example? By all means know that handling should be more than printing the stack trace, but in this case it’s a main method. It’s the end of the line.

Читайте также:  Php streams and sockets

Hi, I hope you enjoy your learning. Learning a new programming language effectively implies learning the idiomatic ways in which to code in that language (even the ones that we subjectively find annoying.)

This is not unique to Java. Whether you do C# or Python or C++ or Haskell, you will be bound to find something that is annoying. Then the question is, what value do you get in the effort to avoid that annoyance.

If you become more productive by avoiding the annoyance, then more power to you. Otherwise, I would follow Maya Angelou’s advice: «If you don’t like something, change it. If you can’t change it, change your attitude.»

And I find it really annoying to keep writing throws IOException in the «main» and all the methods that open a file.

In real life development, you will be handling far more non-main exceptions that main ones (probably only one main.)

So what is the threshold, the ration of main/(all other functions) by which the annoyance is justifiable and constructive? One main and one function? One main and a dozen? One main and a hundred?

Of all the plumbing and elbow grease that needs to be done with Java, declaring exceptions on the main function is an exercise in emotion of very little use.

So take it with a grain of salt, but in my professional opinion (18 years, Java, C++, Python and a lot of other crap) is this: declare your exceptions, even on main.

Why? Because it is possible that other programs might invoke your main. That is, your Java program might be invoked from the console, or it might be embedded (invokable?) from another program.

I’ve done this a lot for testing or for developing systems that are embeddable. So, in this case, you want to declare those exceptions. However, since such a program is intended for standalone and embedded use, this is the general pattern I follow (java-like pseudocode, far more simplified than real-life code):

class UtilityDelegate < UtilitytDelegate()< . >void performWork(File f) throws IOException < // do something with file >> public class SomeUtility < public static void main(final String[] args) throws IOException < File f = null; try< // do something that could throw an exception f = new File(args[0]); performWork(f); >finally < // do necessary clean-up, if any, such as closing file handles, // sockets, flushing database changes, pray to Lord Xenu, whatever if( f != null )< try< f.close(); >catch (IOException e) < e.printStackTrace(); // or use a logging mechanism or whatever >> > > > 

Now, your program can be called from the command line:

Or from another java class:

public class SomeUtilityClient < public static void main(final String[] args)< // for brevity, I'm omitting the case when the utility might // call System.exit() itself. try< SomeUtility.main("a-pre-defined-filename"); >catch(IOException e) < someLog("call to utility failed, see exception", e); System.exit(-1); >System.exit(0); > > 

An argument could be made that such a java client should call the embedded program via another method name, not main. That is fair, and in many cases, it is the better approach.

But just consider this one reason or approach of why to declare your exceptions everywhere, even on your main.

Источник

what does it mean -> public static void main(String[] args) throws IOException

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?

Читайте также:  Java bean string value

The only difference is that there will be nothing to catch the exception since you will be at the top of YOUR class. But there is still the JVM to «print it» and stop the process (just like an RuntimeException that you don’t catch)

4 Answers 4

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); 

You could simply a.main(args); 😉 but should be A.main(args); but I never found the need to call the starting method again.

@AxelH args! (get it?) You’re right I should have just used that instead. Thank you. I’ve re-called the starting method only to fully restart an application without actually closing out of it. A weird trick that can surprisingly work well sometimes. You never know!

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.

 public void iThrowException() throws Exception

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.

Источник

How to properly catch exceptions with java file I/O [duplicate]

I’m trying to become familiar with file I/O in Java. I started off by getting a lot of errors when compiling, such as error: unreported exception IOException; must be caught or declared to be thrown . So I made some changes to the code and ended up with:

public static void main(String[] args)< FileInputStream in = null; FileOutputStream out = null; String content = "hello"; byte[] contentBytes = content.getBytes(); try< out = new FileOutputStream("output.txt"); out.write(contentBytes); >catch(IOException e)< >catch(FileNotFoundException e) < >finally < if (out != null) out.close(); >> 
FileIO.java:16: error: exception FileNotFoundException has already been caught >catch(FileNotFoundException e)< ^ FileIO.java:21: error: unreported exception IOException; must be caught or declared to be thrown out.close(); ^ 2 errors 
  1. Where did I "already catch" FileNotFoundException ?
  2. Because of the second error, do I need to put another try and catch statement in the finally clause to catch IOException ? That seems messy and over-complicated. Am I doing something else wrong? And why doesn't java let me do what I want without forcing me to catch exceptions?
public static void main(String[] args)< FileOutputStream out = null; String content = "hello"; byte[] contentBytes = content.getBytes(); try< out = new FileOutputStream("output.txt"); out.write(contentBytes); >catch(FileNotFoundException e)< >catch(IOException e) < >finally < if (out != null) out.close(); >> 
FileIO.java:20: error: unreported exception IOException; must be caught or declared to be thrown out.close(); ^ 1 error 

Your other question is probably answered here: Java catching exceptions and subclases. Although I'd recommend sticking to one question per post to get better answers for each issue and make the post more useful to others.

Читайте также:  Дано целое трехзначное число найдите сумму его цифр python

@Ravi The post is currently asking two distinct questions - there probably needs to be a rather significant edit to the question body (by the author) to justify a title that focuses on only one of them (although the answers would make such an edit problematic).

@Ravi Pretty much, if you want. Although I don't mind much because I think the question should be closed as too broad or a duplicate.

@Dukeling I rolled back to old change. I thought to make title more meaningful so that people can search easily. But, I agree with your point. 🙂

5 Answers 5

Where did I "already catch" FileNotFoundException?

FileNotFoundException extends IOException , which means IOException can catch FileNotFoundException exception. So, there is no point of FileNotFoundException after it.

Just reverse the order, to resolve this issue.

>catch(FileNotFoundException e)< >catch(IOException e)

Also, don't leave catch block blank, use them to display appropriate message, else you won't have any clue, if you got any exception.

second error, do I need to put another try and catch statement in the finally clause to catch IOException?

Yes. But, I would suggest to use try-with-resource it will take care of closing resource at the end.

As said, you should use try-with-resource instead

try (FileOutputStream out = new FileOutputStream("people.bin");) < out.write(contentBytes); >catch(FileNotFoundException e) < >catch(IOException e)

@Sahand I have noticed many times, you seems to have habit of downvoting immediately. You should have patience and ask back and forth question.

I am not really sure how the compiler let you the code. Could you please try the below code. I dont have any error when i run it.

Answer to the first question is :

Either remove FileNotFoundException line or put it above IOexception.

Answer to the second question is :

if you think that is messy, you can just duck the exception by using Throws i.e. throws IOException next to main(String[] args).

Java(compiler) pushes you to catch or declare your exceptions(using throws) because, the main purpose of Exceptions in java is not running into errors when the code is run. When an exception happens in the finally block, it leads to error and it ultimately impacts your application at run time. Have to very careful when you are closing stuff in Finally block. If you think, the code looks messy, then you can use Throws key word which solves your concern.

 public static void main(String[] args)< FileInputStream in = null; FileOutputStream out = null; String content = "hello"; byte[] contentBytes = content.getBytes(); try< out = new FileOutputStream("output.txt"); out.write(contentBytes); >catch(IOException e) < >finally< if (out != null)< try< out.close(); >catch(IOException e) < >> > > 

Источник

Оцените статью