Solved

Difference between throwing and catching an exception?

Posted on 2006-11-30
13
1,288 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
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 

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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
reverse digits of a number using for loop 5 52
Java syntax, or is it Selenium 6 30
Java basic valueOf question 1 29
Coding for the first time 9 34
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…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

820 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