Solved

Difference between throwing and catching an exception?

Posted on 2006-11-30
13
1,297 Views
Last Modified: 2012-05-05

Hi,

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

Thanks
0
Comment
Question by:mousemat212
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
  • 2
  • +1
13 Comments
 
LVL 5

Accepted Solution

by:
dasmaer earned 100 total points
ID: 18045933
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
0
 
LVL 6

Assisted Solution

by:SamsonChung
SamsonChung earned 50 total points
ID: 18045989
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.
0
 
LVL 9

Assisted Solution

by:matthew016
matthew016 earned 50 total points
ID: 18046016
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.
0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 

Author Comment

by:mousemat212
ID: 18046074

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?
0
 
LVL 5

Expert Comment

by:dasmaer
ID: 18046109
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.

0
 

Author Comment

by:mousemat212
ID: 18046140

What is the difference between:

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

?
0
 

Author Comment

by:mousemat212
ID: 18046151

Assuming of course myMethod throws a check exception.
0
 

Author Comment

by:mousemat212
ID: 18046153

>>Assuming of course myMethod throws a check exception.

sould be

Assuming of course myMethod throws a checked exception.

Thanks!
0
 
LVL 5

Expert Comment

by:dasmaer
ID: 18046166
sniff... sounds like homework.
0
 
LVL 6

Expert Comment

by:SamsonChung
ID: 18046177

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
0
 

Author Comment

by:mousemat212
ID: 18046226


>>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.
0
 
LVL 5

Expert Comment

by:dasmaer
ID: 18046387
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.
0
 

Author Comment

by:mousemat212
ID: 18046550

Thanks everyone
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses

617 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question