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();
}
}
Related
look at the next code lines please:
public void methodBla(){
try{
system.out.println(2/0);
{
catch(MyArithmeticException me){
system.out.println("Error: My exception");
}
catch(Exception a){
system.out.println("Error: general exception");
}
}
I don't understand why, when I'm trying to catch an ArithmeticException with my customize class: MyArithmeticException which extends ArithmeticException.
Public class MyArithmeticException extends ArithmeticException{
public MyArithmeticException(String str){
super("My Exception " + str);
}
}
MyArithmeticException doesnt catch it, its only catch the second "catch"(catch(Exception a)).
Thanks
Z
It is simple, because the statement 2/0 doesn't throw a MyArithmeticException. It throws ArithmeticException and since you didn't catch ArithmeticException, it is catched by the second catch.
The java language doesn't know if you want to derive your own exception type from any language defined exception. So if you need to throw your own type you should catch it and re-throw it as a ArithmeticException:
public void methodBla(){
try{
try{
system.out.println(2/0);
catch(ArithmeticException e){
throw new MyArithmeticException(e);
}
}
catch(MyArithmeticException me){
system.out.println("Error: My exception");
}
catch(Exception a){
system.out.println("Error: general exception");
}
}
Good Luck.
The problem is that an Arithmetic exception would be thrown. Not a "MyAritmeticException" so it cant be caught by the first catch clause, so it results to the second catch clause.
In other words, 2/0 will throw an AritmeticException which is the superclass of your exception thus it will not triger the MyArithmeticException catch block because thats a subclass.
If you want to customise the message of the exception you can do that in the catch statement, where you can get the message by Exception#getMessage() or Exception#getLocalizedMessage(); (the difference of the two can be found here)
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
}
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 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.
In C#, I can use the throw; statement to rethrow an exception while preserving the stack trace:
try
{
...
}
catch (Exception e)
{
if (e is FooException)
throw;
}
Is there something like this in Java (that doesn't lose the original stack trace)?
catch (WhateverException e) {
throw e;
}
will simply rethrow the exception you've caught (obviously the surrounding method has to permit this via its signature etc.). The exception will maintain the original stack trace.
You can also wrap the exception in another one AND keep the original stack trace by passing in the Exception as a Throwable as the cause parameter:
try
{
...
}
catch (Exception e)
{
throw new YourOwnException(e);
}
I would prefer:
try
{
...
}
catch (FooException fe){
throw fe;
}
catch (Exception e)
{
// Note: don't catch all exceptions like this unless you know what you
// are doing.
...
}
In Java is almost the same:
try
{
...
}
catch (Exception e)
{
if (e instanceof FooException)
throw e;
}
In Java, you just throw the exception you caught, so throw e rather than just throw. Java maintains the stack trace.
Stack trace is prserved if you wrap the catched excetion into an other exception (to provide more info) or if you just rethrow the catched excetion.
try{
...
}catch (FooException e){
throw new BarException("Some usefull info", e);
}
something like this
try
{
...
}
catch (FooException e)
{
throw e;
}
catch (Exception e)
{
...
}
public int read(byte[] a) throws IOException {
try {
return in.read(a);
} catch (final Throwable t) {
/* can do something here, like in=null; */
throw t;
}
}
This is a concrete example where the method throws an IOException. The final means t can only hold an exception thrown from the try block. Additional reading material can be found here and here.
I was just having a similar situation in which my code potentially throws a number of different exceptions that I just wanted to rethrow. The solution described above was not working for me, because Eclipse told me that throw e; leads to an unhandeled exception, so I just did this:
try
{
...
} catch (NoSuchMethodException | SecurityException | IllegalAccessException e) {
throw new RuntimeException(e.getClass().getName() + ": " + e.getMessage() + "\n" + e.getStackTrace().toString());
}
Worked for me....:)