Solved

Difference between throwing and catching an exception?

Posted on 2006-11-30
13
1,283 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
  • 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
 

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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
count8 challlenge 13 86
maven java path setting 5 50
firstChar challenge 13 85
Requested array size exceeds VM limit 3 48
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…

759 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now