Call constructor from constructor and catch exceptions - java

I have a constructor which calls another constructor in the same class. The problem is I want to catch Exceptions and throw them onwards to the method that called the first constructor. Yet Java doesn't allow this as the constructor call must be the first statement in the constructor.
public Config(String fn) throws IOException, ExcFormattingError {
theFile = fn;
try { cfRead(); }
catch(FileNotFoundException e) {
//create a new config with defaults.
theConfig = defaultConfig();
create();
} catch (IOException e) {
throw new IOException(e);
} catch (ExcFormattingError e) {
throw new ExcFormattingError();
}
fixMissing(theConfig);
}
public Config() throws IOException, ExcFormattingError {
try {
//Line below is in error...
this("accountmgr.cfg");
} catch (IOException e) {
throw new IOException(e);
} catch (ExcFormattingError e) {
throw new ExcFormattingError();
}
}
If someone could explain how I could do this that would be good. A bonus would be knowing why the language has to behave this way, because that is always interesting.

You don't need those try-catch block inside the constructor (in fact, you can't write it there, as you already figured out). So, change your constructor to:
public Config() throws IOException, ExcFormattingError {
this("accountmgr.cfg");
}
In fact the catch block in your constructor was hardly doing anything productive. It was just re-creating an instance of the same exception, and throwing it. That is really not needed given the fact that, if the exception is thrown, it will automatically propagated to the caller code, where you can handle the exception.
public void someMethod() {
Config config = null;
try {
config = new Config();
} catch (IOException e) {
// handle it
} catch (ExcFormattingError e) {
// handle it
}
}
Having said that, it is rarely a good idea to throw a checked exception from the constructor, even worse handling them in the caller code.
If the exception is thrown, and you handle it in the calling method. Then you are simply ignoring the fact that your instance is not completely initialized. Proceeding with that instance further will result in some unexpected behaviour. So, you should avoid it really.

Related

Java exception handling with instantiate Exception superclass and IOException subclass

First I create a class called OrderHandler.java. I declared an instance of superclass Exception and an instance of subclass IOException in a main method.
Now the question is to show a compilation error when you try catching the superclass exception type before the subclass exception type. What should I do? Need I create some methods to show the path? Or do I need to instantiate the OrderHandler as well?
Thanks
import java.io.IOException;
public class OrderHandler {
public static void main(String[] args) {
// TODO Auto-generated method stub
Exception A = new Exception();
IOException B = new IOException();
}
}
You're not catching any exceptions in your sample code. I think you mean this:
try {
// do some stuff
} catch (Exception ex) {
// report a general exception
} catch (IOException ex) {
// report an IO exception
}
This isn't going to do what you want it to do. You need to catch more specific exceptions first, otherwise the IOException block will never execute. The correct way to do this is:
try {
// do some stuff
} catch (IOException ex) {
// report an IO exception
} catch (Exception ex) {
// report a general exception
}

Try-Catch-Finally Block

i already know that the traditional Try block in java must have at least catch block or finally block (both or either), and i already know that checked exceptions must be handled or declared.
but i am wondering why it won't compile although i have used correct try block syntax
i have this piece of code here , in the main method i used Try with finally block but i am wondering why it won't compile
Here is my code:
import java.io.IOException;
import java.net.Socket;
public class ExHandling {
public void connect() throws IOException
{
Socket s = new Socket();
try
{
s.getInputStream();
}
catch(IOException e )
{
e.printStackTrace();
}
finally
{
s.close();
}
}
public static void main(String []args)
{
ExHandling ex = new ExHandling();
try
{
ex.connect();
}
finally
{
System.out.println("Finally");
}
}
}
Any Help Please
Remove the throws clause from your connect() method. It already catches the IOException. If you declare your method as throwing a checked exception it must be caught upon calling.
Update: since Socket#close() can itself throw an exception, you need to decide what do you want to do about it. Exception handling is hard because people tend to only think about the happiest path a program can take.
If you don't want to catch the exception explicitly in the main() method, you have only one choice: wrap the call to s.close() (and every other method that can throw a checked exception) into its' own try-catch block and remove the throws clause:
public void connect() {
Socket s = new Socket();
try {
s.getInputStream();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
But you should probably think—"what should I do when it fails?"—each time you're dealing with code that might throw.
Either catch the thrown IOException or throw it and let JVM handle the same.
IOException checked exception so you need catch or add an exception to a signature method. final just guarantee whatever happens final block will be executed.
Declare your main method to catch the IOException. If you do so, when the exception is thrown in your connect() method, it will be propagated to the main method and your finally block will be executed. If that is what you wanted.
finally itself cannot handle any exception. So when using try{} finally then the code inside try should either not be raising any exception or your method must be throwing the exception.
It won't compile because just as you indicated, the s.close() in your finally block can throw an IOException and you chose to handle that checked exception by specifying the "throws IOException" clause. Because of that choice, the calling method must handle that checked exception by either catching it or also specifying it will throw the exception.
It is unclear what results you desire other than it must compile, so here are three options:
1) Wrap s.close with it's own try/catch and remove the throws clause.
2) Move "ExHandling ex" definition inside the caller's try/catch.
3) Add a throws clause to the caller (and remove the try/finally if desired). RECOMMENDED
CAUTION: You really don't want to catch an exception and do "e.printStackTrace();". All this does is mask issues in your logic. You should only catch an exception if you plan to handle it in some manner; otherwise, you should allow the exception to propagate up the chain of callers. Thus, only use options 1 & 2 if you really wish to do something in all the catch clauses.
Option 1: Wrap s.close with it's own try/catch and remove the throws clause.
public void connect() {
Socket s = new Socket();
try {
s.getInputStream();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ExHandling ex = new ExHandling();
try {
ex.connect();
}
finally {
System.out.println("Finally");
}
}
Option 2: Move "ExHandling ex" definition inside the caller's try/catch. In this case I would recommend using try with resources for the socket.
public void connect() throws IOException {
Socket s = new Socket();
s.getInputStream();
s.close();
}
public static void main(String[] args) {
try {
ExHandling ex = new ExHandling();
ex.connect();
} catch (IOException e) {
e.printStackTrace();
}
finally {
System.out.println("Finally");
}
}
Option 3: Add a throws clause to the caller (and remove the try/finally if desired). RECOMMENDED
public void connect() throws IOException {
Socket s = new Socket();
s.getInputStream();
s.close();
}
public static void main(String[] args) throws IOException {
ExHandling ex = new ExHandling();
ex.connect();
System.out.println("Finally");
}

Java re-throw Exception

I have a Project with two classes. One Object class and one GUI class.
I would like to throw my own declared Exception if an error occurs.
I have two methods:
public class getValueClass {
private List<Value> liste;
public List<Value> getValues() {
try {
liste = this.getVal();
} catch (ValueException ex) {
System.out.println("EXCEPTION!! " + ex.getMessage());
ex.printStackTrace();
}
return liste;
}
public List<Value> getVal() throws ValueException
{
liste = null;
try {
// initialize list
// do some stuff
//test exception
if(1 == 1)
{
throw new Exception();
}
} catch (Exception ex) {
throw new ValueException("QWE " + ex);
}
return liste;
}
}
Now the exception is thrown and I catch the exception in my getValues Method and print the Message/Stack
But I call the Method getValues in my GUI-Class and I want to catch the Exception there and print some Information in my dialog!
GUI:
public void myMethod()
{
try
{
l = cs.getValues();
}
catch(Exception ex)
{
System.out.println("TEST " + ex.getMessage());
}
}
But I don't get there because I already catch it in the getValues() method.
Is it possible to make it like this WITHOUT adding throws at method declaration for getValues() method? ( I get this method from an interface and will not change it)
You could throw an unchecked RuntimeException such as IllegalArgumentException or customized RuntimeException subclass.
public List<Value> getValues() {
try {
liste = this.getVal();
} catch (ValueException ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
}
return liste;
}
There is a way to do what you want, but I advise against it depending on your intended purpose of ValueException, as it could be the source of future bugs
You can have ValueException extend RuntimeException. The RuntimeException set of exceptions, as the name implies, are thrown at runtime and are not declared at compile time, and need to be explicitly caught. This way you wouldn't have to add a throws declaration to the getValues() method, but would still catch it in your main method.
Disclaimer explained:
The reason I am not a fan of this idea (and RuntimeExceptions in general) is because they're uncaught until explicitly looked for. This in my mind doesn't make for easy-to-use code, and while it has it's very handy uses, I don't feel right using them because of the uncertainty they carry
Again, this is my opinion, not Java's

Catch exceptions without a try block?

I have a lot of custom exceptions that I'm throwing in a specific cases in the code, and I'd like to have one catch block at the bottom of the method to handle them all.
All the exceptions are children of the Exception class CribbageException, so I'd like to have:
public void myMethod(){
if (whatever){
throw new CardException();
}
if (something else){
throw new InvalidCardException();
}
if (scenario 3){
throw new TwoCardsException();
}
catch (CribbageException e) {
System.out.println(e.getMessage());
}
}
But I'm getting a catch without try error.
Is there any way to use this type of exception handling?
Wrap all the throws inside a single try.
public void myMethod(){
try {
if (whatever){
throw new CardException();
}
if (something else){
throw new InvalidCardException();
}
if (scenario 3){
throw new TwoCardsException();
}
}
catch (CribbageException e) {
System.out.println(e.getMessage());
}
}

I am trying to create a file via a button press but i keep running into an error

I am creating a checkbook and am unable to create a file to write to for each separate account. When I try to create the file I get the error "unreported exception IOException; must be caught or declared to be thrown". I try to declare that my action listener method throws an exception but that makes the action listener method no longer able to work. I then tried to create a separate method that creates the file and is called by the button press but i still run into the same error
Here is my code:
public void actionPerformed(ActionEvent e) {
...
if (e.getSource() == create) {
creatNewAccount(name3.getText());
BALANCE = Double.parseDouble(name2.getText());
}
}
public void creatNewAccount(String s) throws IOException {
FileWriter fw = new FileWriter(s + ".txt", false);
}
creatNewAccount is declared as possibly throwing an IOException. IOException is not a RuntimeException, so you must catch it.
if (e.getSource() == create) {
try {
creatNewAccount(name3.getText());
} catch (IOException ie) {
ie.printStackTrace();
// handle error
}
BALANCE = Double.parseDouble(name2.getText());
}
For more information, please read about The Catch or Specify Requirement and Catching and Handling Exceptions.
A few other things I noticed:
- The word you're looking for is create, not creat.
- You're assigning something to BALANCE. Uppercase names are generally reserved for constants. Consider renaming this variable balance.
- Consider more descriptive names for your text fields. name2 and name3 don't really say much.
IOException is a checked exception. Given that you're calling it within an ActionListener, rethrowing the exception is not an option so you need to catch it.
try {
creatNewAccount(name3.getText());
} catch (IOException e) {
e.printStackTrace();
// more exception handling
}
In your actionPerformed() you need to put a try/catch block around the createNewAccount call. What you do with the exception once caught is up to you -- an easy thing to do is to wrap it in a RuntimeException which does not need to be caught (but might foul up your process until you do something more elaborate).
public void actionPerformed(ActionEvent e) {
...
if (e.getSource() == create) {
try {
creatNewAccount(name3.getText());
} catch( IOException ioe) {
System.err.println("Whoops! " + ioe.getMessage());
throw new RuntimeException("Unexpected exception", ioe);
}
BALANCE = Double.parseDouble(name2.getText());
}
}
It's likely you'll just need to catch the exception inside the method:
public void creatNewAccount(String s) {
try{
FileWriter fw = new FileWriter(s + ".txt", false);
} catch (IOException e){
//TODO something to handle the error
}
}

Categories

Resources