I have a problem with creating an outputstream file.
OutputStream output = new FileOutputStream(username + ".txt");
byte buffer[] = data.getBytes();
output.write(buffer);
output.close();
It worked fine, until I made another method:
public void actionPerformed (ActionEvent e) //When a button is clicked
{
if (e.getSource() == encrBtn)
{
menu.setVisible(false);
createProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == decrBtn)
{
menu.setVisible(false);
viewProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == exitBtn)
{
JOptionPane.showMessageDialog(null, "Goodbye!");
System.exit(0);
}
}
}
}
Previously, I put throws Exception at the start of each method that calls upon the
createprofile();
method (in which the output stream is). But now I get
ProfileEncryption_2.java:54: error: actionPerformed(ActionEvent) in ProfileEncryption_2 cannot implement actionPerformed(ActionEvent) in ActionListener
public void actionPerformed (ActionEvent e) throws Exception //When a button is clicked
^
overridden method does not throw Exception
Previously, I was wondering if there was another way to throw the exception: cannot implement actionPerformed(ActionEvent) in ActionListener
But now I think that it would be better to somehow force the outputstream to make the file. I have googled multiple phrasings of this, but I do now know how to do this... the things I found did not work either.
The ActionListener interface does not declare it's actionPerformed method as throwing any type of Exception, you can not change this signature.
You need to catch and manage the exception from within the method.
public void actionPerformed(ActionEvent e) //When a button is clicked
{
if (e.getSource() == encrBtn) {
menu.setVisible(false);
try {
createProfile();
} catch (Exception exp) {
exp.printStackTrace();
JOptionPane.showMessageDialog(this, "Failed to create profile", "Error", JOptionPane.ERROR_MESSAGE);
}
menu.setVisible(true);
} else {
//...
}
}
FileOutputStream is capable of creating the file if it does not exist, but may have issues if the path doesn't or if you don't have adequate permissions to write to the specified location or any number of other possible issues...
You're getting a type mismatch. The ActionListener interface's actionPerformed method does not include a throws Exception clause, therefore you can't include one on the method you override. A simple fix is to catch any Exception thrown, and re-throw it as a RuntimeException. Since RuntimeExceptions are unchecked, you don't need to include it in the throws clause.
public void actionPerformed (ActionEvent e) //When a button is clicked
{
try { // <-- Added try block
if (e.getSource() == encrBtn)
{
menu.setVisible(false);
createProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == decrBtn)
{
menu.setVisible(false);
viewProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == exitBtn)
{
JOptionPane.showMessageDialog(null, "Goodbye!");
System.exit(0);
}
}
}
}
catch (Exception e) { // <-- Catch exception
throw new RuntimeException(e); // <-- Re-throw as RuntimeException
}
}
It's usually better to actually handle the exception if possible, but if you just want to see the exception (e.g. for debugging), then I'd say wrapping it in a RuntimeException and re-throwing it is a little cleaner than just adding throws Exception on the end of all your method signatures. It's also better if you can narrow the type of Exception in the catch block down to the actual exception types you're expecting.
Related
I have two methods. Method A calls method B. I cannot change the exceptions of neither (homework demands). However, the 2 exceptions mean the exact same thing, so when I call method B on A, I already know that B's exception is not getting thrown. However, I still get the "unhandled exception" error from Eclipse. How can I avoid it?
Here are the methods
public void createProfile(Profile user) throws PEException {
Vector<Profile> p = new Vector<Perfil>();
try{
if (repository.search(user.getUsername()) == null) {
repository.register(user); //error on this line when I call the method on main
}
else {
throw new PEException(user.getUsername());
}
} catch (PEException e){
e.printStackTrace();
}
}
public void register(Profile user) throws UJCException {
try {
if (this.search(user.getUsername()) == null) {
this.users.add(user);
}
else {
throw new UJCException(user.getUsername());
}
} catch (UJCException e) {
e.printStackTrace();
}
}
I MUST NOT change the definitions of the methods (I can't throw UJCException on createProfile). Thanks in advance
You shouldn't be throwing the exceptions and then catching them inside the same method. That defeats the purpose of throwing the exception in the first place. the methods which calls your 2 methods should expect nothing (void) or the exception in the event that something went wrong. Make sure your methods createProfile() and register() can actually throw their exception so methods calling them can catch the exception and do whatever it is they need to when the exception is thrown.
public void createProfile(Profile user) throws PEException {
Vector<Profile> p = new Vector<Perfil>(); //not being used...
if (repository.search(user.getUsername()) == null) {
try{
repository.register(user);
}catch(UJCException e){
e.printStackTrace();
throw new PEException(user.getUsername());
}
}
else {
throw new PEException(user.getUsername());
}
}
public void register(Profile user) throws UJCException
{
if (this.search(user.getUsername()) == null) {
this.users.add(user);
}
else {
throw new UJCException(user.getUsername());
}
}
Now when you call these methods wrap the call in a try catch and catch the appropriate exception depending on which method was called
I would like to ask about a problem i encountered while trying to make a method which can read text from a file.
For example, I created a simple interface, when you click the buttons, the text with a predefined folder path will be read.
So i use actionListener like this. Note that "einlesen" is "read" in German.
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == einlesenDatei)
{
this.einlesen();
}
if (source == decoder)
{
this.decode();
}
}
The problem is, the readInput method required me to throw a FileNotFoundException, and the actionPerformed method requires me to cut off the throw exception part.
You can put the code for read method in a try catch block like this:
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == inputFile) {
try {
this.readInput();
} catch (FileNotFoundException e) {
// handle the exception
}
}
if (source == decoder) {
this.decode();
}
}
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
}
}
I'm trying to fix an issue, in my application I have this code
try {
object1.method1();
} catch(Exception ex) {
JOptionPane.showMessageDialog(nulll, "Error: "+ex.getMessage());
}
and the object1 would do something like that:
public void method1() {
//some code...
throw new RuntimeException("Cannot move file");
}
I get a messsage in my option pane like this:
Error: java.lang.RuntimeException: Cannot move file
but I used getMessage and not toString method, so the name of the class shouldn´t appear, right?
What I am doing wrong?
I already tryied with a lot of exceptions, even Exception itself. I'm looking to solve this no without the need to implement my own Exception subclass
PROBLEM SOLVED - thank you all!
The try and catch were actually being called in get() method from SwingWorker which constructs an ExecutionException with my exception thrown from doInBackground()
I fixed doing this:
#Override
protected void done() {
try {
Object u = (Object) get();
//do whatever u want
} catch(ExecutionException ex) {
JOptionPane.showMessageDialog(null, "Error: "+ex.getCause().getMessage());
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage());
}
}
I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:
public static void main(String[] args) {
try {
throw new RuntimeException("Cannot move file");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
}
}
...you will see a popup that says exactly what you want.
However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause:
public static void main(String[] args) {
try {
throw new Exception(new RuntimeException("Cannot move file"));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,
"Error: " + getRootCause(ex).getMessage());
}
}
public static Throwable getRootCause(Throwable throwable) {
if (throwable.getCause() != null)
return getRootCause(throwable.getCause());
return throwable;
}
Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.
My guess is that you've got something in method1 which wraps one exception in another, and uses the toString() of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.
Here's a short but complete program which demonstrates RuntimeException.getMessage() behaving correctly:
public class Test {
public static void main(String[] args) {
try {
failingMethod();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private static void failingMethod() {
throw new RuntimeException("Just the message");
}
}
Output:
Error: Just the message
This question already has an answer here:
What does "error: unreported exception <XXX>; must be caught or declared to be thrown" mean and how do I fix it?
(1 answer)
Closed 8 months ago.
Error:
filecontent.java:15: unreported exception java.io.IOException; must be
caught or
declared to be thrown
showfile();
^ filecontent.java:78: unreported exception java.io.IOException; must be caught or declared to be
thrown
showfile();
^
I have already thrown java.io.IOException, but still it shows these errors.
My code:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class filecontent extends Frame implements ActionListener
{
TextField t[] = new TextField[4];
TextArea ta[] = new TextArea[4];
Button submit;
Panel p1;
filecontent()
{
setGUI();
setRegister();
showfile();
setTitle("FileData");
setVisible(true);
setSize(300, 300);
/* addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
*/
}
void setGUI()
{
p1 = new Panel();
p1.setLayout(new GridLayout(5, 4, 10, 10));
for(int i=0; i<4; i++)
{
t[i] = new TextField(10);
ta[i] = new TextArea("");
p1.add(t[i]);
p1.add(ta[i]);
}
submit = new Button("Submit");
p1.add(submit);
}
void setRegister()
{
submit.addActionListener(this);
}
void showfile() throws java.io.IOException
{
FileReader fin[] = new FileReader[4];
FileReader fn;
// br[]=new BufferedReader[4];
for(int i=0;i<4;i++)
{
fin[i]=new FileReader(t[i].getText());
}
int cnt = 1;
String s;
fn = fin[0];
BufferedReader br = new BufferedReader(fn);
while(cnt <= 4)
{
if((s=br.readLine()) != null)
{
ta[cnt-1].append(s+"");
}
else
{
cnt++;
fn = fin[cnt-1];
ta[cnt-1].setText("");
}
}
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==submit)
{
showfile();
}
}
public static void main(String ar[])
{
new filecontent();
}
}
void showfile() throws java.io.IOException <-----
Your showfile() method throws IOException, so whenever you use it you have to either catch that exception or again thorw it. Something like:
try {
showfile();
}
catch(IOException e) {
e.printStackTrace();
}
You should learn about exceptions in Java.
Exceptions bubble up the stack. If a caller calls a method that throws a checked exception, like IOException, it must also either catch the exception, or itself throw it.
In the case of the first block:
filecontent()
{
setGUI();
setRegister();
showfile();
setTitle("FileData");
setVisible(true);
setSize(300, 300);
/*
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
*/
}
You would have to include a try catch block:
filecontent()
{
setGUI();
setRegister();
try {
showfile();
}
catch (IOException e) {
// Do something here
}
setTitle("FileData");
setVisible(true);
setSize(300, 300);
/*
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
*/
}
In the case of the second:
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == submit)
{
showfile();
}
}
You cannot throw IOException from this method as its signature is determined by the interface, so you must catch the exception within:
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==submit)
{
try {
showfile();
}
catch (IOException e) {
// Do something here
}
}
}
Remember, the showFile() method is throwing the exception; that's what the "throws" keyword indicates that the method may throw that exception. If the showFile() method is throwing, then whatever code calls that method must catch, or themselves throw the exception explicitly by including the same throws IOException addition to the method signature, if it's permitted.
If the method is overriding a method signature defined in an interface or superclass that does not also declare that the method may throw that exception, you cannot declare it to throw an exception.
The error message means that any method that calls showfile() must either declare that it, in turn, throws IOException, or the call must be inside a try block that catches IOException. When you call showfile(), you do neither of these; for example, your filecontent constructor neither declares IOException nor contains a try block.
The intent is that some method, somewhere, should contain a try block, and catch and handle this exception. The compiler is trying to force you to handle the exception somewhere.
By the way, this code is (sorry to be so blunt) horrible. You don't close any of the files you open, the BufferedReader always points to the first file, even though you seem to be trying to make it point to another, the loops contain off-by-one errors that will cause various exceptions, etc. When you do get this to compile, it will not work as you expect. I think you need to slow down a little.
Your method showFile() declares that it can throw an IOException. Since this is a checked exception, any call to showFile() method must handle the exception somehow. One option is to wrap the call to showFile() in a try-catch block.
try {
showFile();
}
catch(IOException e) {
// Code to handle an IOException here
}
When the callee throws an exception i.e. void showfile() throws java.io.IOException the caller should handle it or throw it again.
And also learn naming conventions. A class name should start with a capital letter.