Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Throw and catch exception in 2 classes

Reply
Thread Tools

Throw and catch exception in 2 classes

 
 
Matt
Guest
Posts: n/a
 
      06-10-2004
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!!
 
Reply With Quote
 
 
 
 
Andy Fish
Guest
Posts: n/a
 
      06-10-2004
"Matt" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed) m...
> 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.

> Please advise. Thanks!!



 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
catch(Exception* e){ throw;} generate error Daimler C++ 7 01-26-2007 07:43 AM
JNI's throw new does not throw an exception yarona@m-sys.com Java 15 09-08-2005 08:36 AM
Try-catch not working - why does this throw an Exception? Jon Maz ASP .Net 7 10-25-2004 04:55 PM
try-catch & throw Exception Question Matt Java 1 06-12-2004 10:33 AM
Throw Exception Vs Throw New Exception Kerri ASP .Net 2 10-27-2003 02:13 PM



Advertisments