Throw and catch exception in 2 classes

M

Matt

I am new to exceptions. I have 2 classes A and B, and process() method in class
A will call generateString() method in class B. Exception can happen in class B,
and class A needs to take care of that exception. Below is my code so far,
but not sure what I do in the comment I put below.

public class A
{
public void process()
{
try
{ B b = new B();
String response = b.generateString("a string");
}
catch()
{ //catch exception from class B
}
}
}

public class B
{
public String generateString(String s)
{ //can throw exception if generation has problem
}
}


Please advise. Thanks!!
 
A

Andy Fish

Matt said:
I am new to exceptions. I have 2 classes A and B, and process() method in class
A will call generateString() method in class B. Exception can happen in class B,
and class A needs to take care of that exception. Below is my code so far,
but not sure what I do in the comment I put below.

public class A
{
public void process()
{
try
{ B b = new B();
String response = b.generateString("a string");
}
catch()
{ //catch exception from class B
}
}
}

public class B
{
public String generateString(String s)
{ //can throw exception if generation has problem
}
}

An exception is an object like any other. to distinguish your exception from
others you will probably want to create your own subclass of Exception (say
MyException). then declare the method generateString as

public String generateString(String s) throws MyException

when you want to throw the exception inside the method, you simply

throw new MyException(...);

and to catch it inside A, you need to do

try {
...
} catch (MyException ex) {
... do stuff with ex
}

I would advise you to read up about exceptions in a book or suchlike before
you start using them in earnest though.
 

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

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top