Difference between throwing and catching an exception?


Hi,

What is the difference between throwing an exception and catching an exception?

Thanks
mousemat212Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

dasmaerCommented:
Hi Mousemat

When you catch an exception you are catching something that is out of your control or (semi/un)-expected.

When you throw an exception you are causing the Exception yourself so that you can catch it later.

For example

try{
  //do some IO stuff
  throw IOException; // throw IO exception for no reason
}
catch(IOException e){
  //catch the IOException you just threw.
}
catch(Exception c){
  //catch any other exception
}

It is useful if you are building your own class and what to create your own Exceptions for use in your code.

D

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
SamsonChungCommented:
Exceptions are kinda like a short cut out of a sticky situation.

If you catch one, someone wrote a piece of code that simply states 'You input to my code is not causing some unexpected problems, I am going to tell you why instead of dying on you'

When you throw an exception, you are simply saying 'You can use my code in yours, however, you are now on my field and therefore must play according to my rules, if you don't, I'll simply kick you out'

So, basically Catching an exception is to allow your program to have error handling, whereas throwing the exception is actually doing the error handling,

for example,

if my code takes a person's name in english and translates it to french, some one who doesn't know the limitations can easily pass in a Russian name.
My code will then see this and throw an exception saying 'only english names allow';

the person who is using my code will then see this informaiton by 'catching' the exception.
matthew016Commented:
Actually,

u need to throw an exception if u don't want to handle the error in the class where the error occured,
then u can catch it in another class to handle the error.


Why would someone decide to catch the exception later ?

Take for example a GUI application (an application with a user interface),
and let's say u have a class that connects to a database.
If a conenction error occurs, u don't want to catch the exception in this class,
but u want to catch it in the interface to show the errors to the user.

I hope it is clear.
Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

mousemat212Author Commented:

Thanks for the replys,

ok, so throwing an exception is like letting the jvm display the stack trace, if the exception is thrown, and catching an exception is performing your own custom handling code to deal with the exception?
dasmaerCommented:
yes, when you catch the exception in a catch block you'll information from the stack trace in your variable (in my example "e"), so you can still display your stack without your app dying.

mousemat212Author Commented:

What is the difference between:

private void myMethod() throws IOException
and
private void myMethod()
{
//do stuff
}
catch(IOException e)
{
e.printStackTrace();
}

?
mousemat212Author Commented:

Assuming of course myMethod throws a check exception.
mousemat212Author Commented:

>>Assuming of course myMethod throws a check exception.

sould be

Assuming of course myMethod throws a checked exception.

Thanks!
dasmaerCommented:
sniff... sounds like homework.
SamsonChungCommented:

private void myMethod() throws IOException

this is the originator

let's say it is in class mousemat212

Now the following is in mousemat140
private void myMethod()
{
try{
  //do stuff
  x = new mousemat212();
  x.myMethod();
  //code 2
}catch(IOException e){
  e.printStackTrace();
}

at this point, if mousemate212.myMethod simply throws an IOException, e.printStackTrace will be ran instead code 2
mousemat212Author Commented:


>>sniff... sounds like homework.

Nope its not homework.

This is my complete method:
    private void setAmt(HttpSession session) throws IOException
    {
        Properties properties = new Properties();
        String amtItemsPerPage = null;
        try
        {
            properties.load(new FileInputStream("myProp.properties"));
            number = properties.getProperty("***.***");
            Integer.parseInt(number);    
        }
        catch (NumberFormatException numberFormatException)
        {
            log.error("Could not convert value to Integer, numberFormatException);
        }
        catch (FileNotFoundException notFoundException)
        {
            log.error("Could not find property at file",notFoundException);
        }
    }

I was just getting confused at what the point was of throwing an IOException (the compiler forces me too) when im catching the exceptions that im worried about.
dasmaerCommented:
Sometimes the compiler needs to know that a certain kind of exception will be thrown (although you can specify "throws" on any kind of class).

Have a look at: http://www.artima.com/designtechniques/exceptions.html and the Exceptions part of here is quite good too: http://www.cs.wisc.edu/~cs536-1/NOTES/JAVA/Exceptions.html

Alternatively Google: "in java why throw an exception", some relevent hits come up.
mousemat212Author Commented:

Thanks everyone
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.