As the title suggests I am trying to catch an empty String. I have a class (the class of the object I am trying to create) that throws an Exception when the String is null or empty (check with str.isEmpty).
When I try to create the object with an empty String in another class it works as intended and throws an Exception. However, I want this class to Catch that Exception and notify the user. But it never seems to Catch the Exception, even if I try to write Catch(Exception exc).
Now I know a null or empty String is not illegal. But my intention was that the object class was supposed to make it so. Instead it seems as if the catch block doesn't care at all. I am starting to think that I would have to create my own exception class of some sort... or is there something I am missing? Here are the relevant parts of the code:
The object class constructor:
public Valueables(String name){
//name.trim().length() == 0
if(name == null || name.isEmpty()){
try {
throw new Exception("Subclasses of Valueables cannot take in an empty String or null value for the \"name\" constructor");
} catch (Exception e) {
e.printStackTrace();
System.exit(2);
}
}
else
this.name = name;
}
The other class (the new Trinket object is a subclass of Valueables. The one with the constructor code above):
while(loopPassErrorControl == false){
//I don't think the try loop is relevant. But just to make sure...
//Otherwise just ignore it
try{
TrinketForm Tform = new TrinketForm();
answer = JOptionPane.showOptionDialog(ValueablesFrame.this, Tform, "Nytt smycke", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options , null);
if (answer != JOptionPane.OK_OPTION){
return;
}
valueablesList.add(new Trinket(Tform.getName(), Tform.getGemstones(), Tform.getMetalSelected()));
loopPassErrorControl = true;
}catch(NumberFormatException | NullPointerException exc) {
JOptionPane.showMessageDialog(ValueablesFrame.this, "NĂ¥got gick fel");
}
}
//Test
for(Valueables obj : valueablesList){
System.out.println(valueablesList);
}
First throw a RuntimeException on Valuable:
public Valueables(String name){
//name.trim().length() == 0
if(name == null || name.isEmpty()){
throw new RuntimeException("Subclasses of Valueables cannot take in an empty String or null value for the \"name\" constructor");
}
else
this.name = name;
}
And do not catch the exception.
Second, on the other class catch a RuntimeException and show a mesage:
...}catch(RuntimeException exc) {
JOptionPane.showMessageDialog(exc.getMessage());
}
Hope helped you!
Already made a question about empty strings, an empty string is still not null so it must throw "IllegalArgumentException" if you WANT to catch it.
try to catch it as the generic Exception, replace the NuumberFormatException and NullpointerException.
You can also do this in Java.
try {
//Some Code here
} catch (NumberFormatException | NullPointerException ex) {
//Handle NumberFormat and NullPointer exceptions here
} catch (Exception ex) {
//Handle generic exception here
}
Related
I have a string variable that has a full qualified exception name. I want to check in catch block if exceptions occur whether it is an instance of exception that mentioned in string or not. How to solve that
String stringEx = "org.hibernate.StaleStateException";
try {
// program
} catch (Exception ex) {
if (e instanceof stringEx) { //<-- How to convert string to exception class
// do specific process
}
}
Maybe you need this:
String stringEx = "org.hibernate.StaleStateException";
try {
// program
} catch (Exception ex) {
if (Class.forName(stringEx).isInstance(ex)) {
// do specific process
}
}
I am creating a kind of messenger program, where clients communicate with the server etc.
The problem I have stumbled upon is when trying to create the ObjectInputStream and the ObjectOutputStream. Here is the method that instantiated the object streams:
private void initializeStreams() {
try {
input = new ObjectInputStream(socket.getInputStream());
if (input != null) {
System.out.println("ObjectInputStream successfully initiated");
} else {
System.out.println("ObjectInputStream is null but did not return an exception when being instantiated");
}
} catch (IOException ioe) {
System.out.println("Could not initialize ObjectInputStream: " + ioe.getMessage());
}
try {
output = new ObjectOutputStream(socket.getOutputStream());
if (output != null) {
System.out.println("ObjectOutputStream successfully initiated");
} else {
System.out.println("ObjectOutputStream is null but did not return an exception when being instantiated");
}
} catch (IOException ioe) {
System.out.println("Could not initialize ObjectOutputStream: " + ioe.getMessage());
}
}`
The problem within this method is that NONE of the System.out.println() methods are getting called, even though, at least to my knowledge, one for each of the streams should be getting called. For example, when instantiating the ObjectInputStream, it should either throw an Exception (which it apparently does not because the System.out.println() is not getting called), returning null (which also does not seem to be the case because the System.out.println() is not getting called) or successfully create the ObjectInputStream object, which it does not because the System.out.println() is not getting called. Why does it not run into any of these situations? Am I missing another situation that might occur?
P.S. Yes, the initializeStreams() method is being called from the program, I just checked it putting a System.out.println() at the very first line of the method.
Thank you
Try to write something on the console in the finally-cluster.
What possibly could be is that an exception is thrown, which doesn't get catched.
But you would see that...wouldn't you.
My first tip: Debug your program, that's what often helped me.
But you could also try this:
private void initializeStreams() {
input = null;
output = null;
try {
input = new ObjectInputStream(socket.getInputStream());
}
} catch (IOException ioe) {
System.out.println("Could not initialize ObjectInputStream: " + ioe.getMessage());
}
//just copied the if outside of the try-catch-cluster
if (input != null) {
System.out.println("ObjectInputStream successfully initiated");
} else {
System.out.println("ObjectInputStream is null but did not return an exception when being instantiated");
try {
output = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException ioe) {
System.out.println("Could not initialize ObjectOutputStream: " + ioe.getMessage());
}
if (output != null) {
System.out.println("ObjectOutputStream successfully initiated");
} else {
System.out.println("ObjectOutputStream is null but did not return an exception when being instantiated");
}
}`
Thats one thing I would try in order to find out what or where the problem is.
Even if it doesn't make that much sense ;)
Well, you catch only IOException. There might be RuntimeException for instance in your code. You won't get to your catch block in this case.
Change IOException to Exception and you will see the reason.
new ObjectInputStream() can throw exceptions other than IOException, but your try-catch only captures IOException. What happens if the exception thrown is one of the other types?
Replace IOException with the Exception class which is the parent of all exception classes.Whatever may be the exception,it will surely get caught using Exception class in catch block.
So replace catch (IOException ioe) this with catch (Exception ioe) everywhere in your code.Then u may find where is the exception coming from.
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
I have helper class in which I have written this function.
public static String createProject(Map<String, String> params,String projectName, String projectPrefix) {
String createdProject = null;
try {
createdProject=//logic for creating createdProject string which may throw two exception mentioned below
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (TestLinkAPIException t) {
t.printStackTrace();
}
return createdProject;
}
now I am calling this function from GUI part where I have written
String createProject=//called above function.
now If error occur in above code I want to show error to the user.
my question is how I get back the created string and error message if some Exception occur
Create a Custom Exception
Add your String value as an instance field of that Custom Exception.
Throw the custom exception with the String values passed in.
Now you have the exception and the String as well.
If you have a Java 7, then you can use Multi-Catch exception block.
public static String createProject(Map<String, String> params,String projectName, String projectPrefix) throws Exception {
String createdProject = null;
try {
createdProject=//logic for creating createdProject string which may throw two exception mentioned below
} catch (MalformedURLException | TestLinkAPIException e) {
e.printStackTrace();
throw new Exception("Error creating createdProject", e);
}
return createdProject;
}
If exception occurs, createdProject is never set.
You should throw the exception from this method and catch it in block where you calling this method.
public static String createProject(Map<String, String> params,String projectName, String projectPrefix) throws Exception {
String createdProject = null;
try {
createdProject = doSomething();
} catch (Exception e) {
throw new Exception("Error creating Project");
}
return createdProject;
}
and where you calling this method you will have something like this.
try {
String str = createProject();
displayTheProjectCreated(str);
} catch (Exception e) {
// Oops something went wrong
displayErrorMessage(e);
}
How would I manually throw an IndexOutOfBoundsException in Java and optionally print a message?
You simply:
throw new IndexOutOfBoundsException("your message goes here");
If you need to print that message, do so from where you catch the exception. (You can reach the message with the getMessage() method.)
Like this:
throw new IndexOutOfBoundsException("If you want a message, put it here");
This doesn't actually print the message; it just prepares it. To print the message, do something like the following:
try {
//...
throw new IndexOutOfBoundsException("If you want a message, put it here");
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
In the future, I'd suggest looking around for an answer before posting.
You can use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement.
throw someThrowableObject;
Example:
public void example() {
try{
throw new IndexOutOfBoundsException();
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}