Array of Exceptions

P

pascal

Is is possble to create an array of exceptions.
Something like this:

public Object [] x = new Object [10];
Exception [] x = new Exception [10];

x [0] = IllegalMyException;
..
..
..

public void y () throws x[0]
{
throw new x[0];
}

try { y(); }
catch {x[0] e}



The above doesn't work. But is it because I have the syntax wrong, or
it is simply not possible?
 
J

Joshua Cranmer

Is is possble to create an array of exceptions.
Something like this:

public Object [] x = new Object [10];
Exception [] x = new Exception [10];

x [0] = IllegalMyException;
x[0] = new IllegalMyException();
.
.
.

public void y () throws x[0]
No. This is impossible: the throws clause must be determinable at
runtime, not at compile time.
{
throw new x[0]; throw x[0] would work.
}

try { y(); }
catch {x[0] e}
See above comment for the throws clause.
The above doesn't work. But is it because I have the syntax wrong, or
it is simply not possible?

Strictly speaking, you can use arrays of Exceptions like any object.
However, you can not use them for what you're trying to use them. All
throws and catch must involve formal parameters (cf. JLS 1.3 §14.20 and
§8.4.6).
 
A

Alan Cui

Actually, I believe we could declare a "throws" clause with a
superclass of these arrayed exceptions. For simplicity, we could just
declare as "throws Exception".


Is is possble to create an array of exceptions.
Something like this:
public Object [] x = new Object [10];
Exception [] x = new Exception [10];
x [0] = IllegalMyException;

x[0] = new IllegalMyException();> .
public void y () throws x[0]

No. This is impossible: the throws clause must be determinable at
runtime, not at compile time.> {
throw new x[0];

throw x[0] would work.> }
try { y(); }
catch {x[0] e}

See above comment for the throws clause.


The above doesn't work. But is it because I have the syntax wrong, or
it is simply not possible?

Strictly speaking, you can use arrays of Exceptions like any object.
However, you can not use them for what you're trying to use them. All
throws and catch must involve formal parameters (cf. JLS 1.3 §14.20 and
§8.4.6).
 
T

Tom Hawtin

Exception [] x = new Exception [10];

x [0] = IllegalMyException;

What is IllegalMyException? It doesn't look like an instanceof Exception.
public void y () throws x[0]

You can use a fixed number of generic type parameters as exception types
in the exception part of a method declaration.

For instance:

interface Disposable<EXC extends Throwable> {
void dispose() throws EXC;
}

class SQLThing implements Disposable<java.sql.SQLException> {
...
public void dispose() throws java.sql.SQLException {
...
}
}

class NonThrowingThing implements Disposable<java.lang.RuntimeException> {
...
public void dispose() {
...
}
}

Did you have a particular use in mind?

Tom Hawtin
 
D

Daniel Pitts

Is is possble to create an array of exceptions.
Something like this:

public Object [] x = new Object [10];
Exception [] x = new Exception [10];

x [0] = IllegalMyException;
.
.
.

public void y () throws x[0]
{
throw new x[0];

}

try { y(); }
catch {x[0] e}

The above doesn't work. But is it because I have the syntax wrong, or
it is simply not possible?

No, but you could do this:

public interface ExceptionFactory<E extends Exception> {
E createException();
}

public class IllegalMyExceptionFactory implements
ExceptionFactory<IllegalMyException> {
public IllegalMyException createException() {
return new IllegalMyException();
}
}

ExceptionFactory[] exceptionFactories = new ExceptionFactory[] {
new IllegalMyExceptionFactory();
}

public void y() throws Exception {
throw exceptionFactories[0].createException
}
 
P

pascal

No, but you could do this:
public interface ExceptionFactory<E extends Exception> {
E createException();

}

public classIllegalMyExceptionFactoryimplements
ExceptionFactory<IllegalMyException> {
public IllegalMyException createException() {
return new IllegalMyException();
}
}

ExceptionFactory[] exceptionFactories = new ExceptionFactory[] {
newIllegalMyExceptionFactory(); <--- Syntax error expecting }
}

public void y() throws Exception {
throw exceptionFactories[0].createException
}

This almost worked. But I get a syntax error saying it expects a
closing brace.
Have you tried this code? Can you post a working version?
 
D

Daniel Pitts

No, but you could do this:
public interface ExceptionFactory<E extends Exception> {
E createException();

public classIllegalMyExceptionFactoryimplements
ExceptionFactory<IllegalMyException> {
public IllegalMyException createException() {
return new IllegalMyException();
}
}
ExceptionFactory[] exceptionFactories = new ExceptionFactory[] {
newIllegalMyExceptionFactory(); <--- Syntax error expecting }
}
public void y() throws Exception {
throw exceptionFactories[0].createException
}

This almost worked. But I get a syntax error saying it expects a
closing brace.
Have you tried this code? Can you post a working version?

Hmm, you somehow lost a space on that line, also you probably should
have the ; there.
 
P

pascal

// Here now is actually what I have.
public interface ExceptionFactory <E extends Exception>
{
E createException();
}
class IllegalMyExceptionFactory implements ExceptionFactory
<IllegalExceptionA>
{
public IllegalExceptionA createException()
{
return new IllegalExceptionA();
}
}
class MyProgram
{
ExceptionFactory [] exceptionFactories = new ExceptionFactory[]
{
new IllegalMyExceptionFactory()
};

public void y() throws Exception
{
throw exceptionFactories[0].createException();
}
public void x() throws Exception
{
throw exceptionFactories[1].createException ();
}
}

/*
Note I am trying to set up an array of lets say a dozen exceptions
that can be called
*in a manner that you show for method "y". But how do you initialise
the array to each
*one of these exception? I don't see how exceptionFactories[1] will
know
*anything about IllegalExceptionB.
*/
class IllegalExceptionA extends Exception
{
IllegalExceptionA ()
{
super ("IllegalExceptionA ");
}
}
class IllegalExceptionB extends Exception
{
IllegalExceptionB ()
{
super ("IllegalExceptionB ");
}
}
class IllegalExceptionC extends Exception
{
IllegalExceptionC ()
{
super ("IllegalExceptionC ");
}
}
 
T

Tom Hawtin

pascal said:
public interface ExceptionFactory <E extends Exception>
ExceptionFactory [] exceptionFactories = new ExceptionFactory[]

Arrays of generic types aren't pretty. These days there isn't a great
deal of point using arrays of references. Stick with Lists or other
collections, and it'll tend to be much simpler.
public void y() throws Exception
{
throw exceptionFactories[0].createException();
}

The type of exceptionFactories[0] is ExceptionFactory<? extends
Exception>. You could refine the code with say:

class MyProgram<T extends Exception> {
private final List<ExceptionFactory<T>> exceptionFactories...

public void y() throws T {
throw exceptionFactories.get(0).createException();
}

It's no different from a generic parameter used as a return or parameter
type. You can't say element number n of a collection has a particular
static type. Perhaps you are trying to use an array as a substitute for
introducing a new class.

Tom Hawtin
 
P

pascal

I got it to work...
Thanks to all, you provide the key ideas to get this to work.
You can cut and paste the following code into an IDE.
Hit the go button and the exception thrown depends on the array index
of the exception array.
Change the call to the method from x to y to z to see the effect.
I can now take these ideas and incorporate them into my program.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class MyProgram extends JFrame implements ActionListener
{
private JButton go = new JButton ("Go");
private Container pc = getContentPane();

Exception [] exceptionFactories = new Exception []
{
new IllegalExceptionA(),new IllegalExceptionB (), new
IllegalExceptionC ()
};

public void y() throws Exception
{
throw exceptionFactories[0];
}
public void x() throws Exception
{
throw exceptionFactories[1];
}
public void z () throws Exception
{
throw exceptionFactories [2];
}
public static void main (String [] args)
{
MyProgram p4 = new MyProgram ();
p4.setSize(640,480);
p4.setVisible(true);
p4.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public MyProgram ()
{
pc.add (go);
go.addActionListener (this);
}
public void actionPerformed (ActionEvent e)
{
try
{
x();
}
catch (Exception exp)
{
System.out.println (exp.toString ());
}
}
}

class IllegalExceptionA extends Exception
{
IllegalExceptionA ()
{
super ("IllegalExceptionA ");
}
}
class IllegalExceptionB extends Exception
{
IllegalExceptionB ()
{
super ("IllegalExceptionB ");
}
}
class IllegalExceptionC extends Exception
{
IllegalExceptionC ()
{
super ("IllegalExceptionC ");
}
}
 
L

Lew

pascal said:
I got it to work...
Thanks to all, you provide the key ideas to get this to work.
You can cut and paste the following code into an IDE.
Hit the go button and the exception thrown depends on the array index
of the exception array.
Change the call to the method from x to y to z to see the effect.
I can now take these ideas and incorporate them into my program.

Bravo.

The approach I use is to declare one or two project-specific exceptions, one
checked and the other unchecked, e.g., FabulatorException and
FabulatorRuntimeException. Whenever the code catches a lower-level exception,
e.g., IOException, if I must rethrow it I rethrow the standard one with the
original one as the cause.

catch ( IOException ex )
{
String msg = "Some sensible log message with project-specific information. "
+ ex.getMessage();
logger.error( msg );
logger.debug( ex.getStackTrace() );
closeExternalResources();
throw new FabulatorException( msg, ex );
}

The times when I would rethrow a checked exception are few and far between in
any event.

catch ( IOException ex )
{
String msg = "Some sensible log message with project-specific information. "
+ ex.getMessage();
logger.error( msg );
logger.debug( ex.getStackTrace() );
closeExternalResources();
return ERROR;
}

The problems with the array approach are its verbosity and the reduction in
self-documentativity of the source. With only one custom Exception (or one
each of checked and unchecked), an array is completely superfluous anyhoo.

-- Lew
 
D

Daniel Pitts

I got it to work...
Thanks to all, you provide the key ideas to get this to work.
You can cut and paste the following code into an IDE.
Hit the go button and the exception thrown depends on the array index
of the exception array.
Change the call to the method from x to y to z to see the effect.
I can now take these ideas and incorporate them into my program.
Oh, you weren't just asking a theory question?

I would then ask WHY you are doing this? The design looks error prone
and unmaintainable. What reasons do you have to use this
(anti-)pattern?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top