Click here to Skip to main content
15,905,419 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
What is the purpose of using try catch and throws in c++ or java?
Posted
Comments
anamicaa 14-Feb-14 1:54am    
Actually its a syntax for java.io.* are its having any reason?
anamicaa 14-Feb-14 1:56am    
bocs if using import java util.*; we dont use try catch and all.bt y we are using in import java,io.*?
anamicaa 25-Feb-14 6:52am    
ya thank u very nw 1y came to knw to tat no package required for try and cathch.Bcos when I did prgming I came to knw to tat.any thanks for all
[no name] 14-Feb-14 1:57am    
What have you found out so far? Google is quite informative. What did it leave out?
Philippe Mori 16-Feb-14 19:25pm    
I think you can use Google and search yourself...

We use try/catch to wrap operations that could cause exceptions so that we can deal with them. There's a general rule that you should only catch an exception if you are going to do something with it - such as log the exception, or retry the operation that caused the exception in the first place. If you can't handle the exception, you should let it bubble up through the application.

Now, in order to get an exception, something has to throw it - and that's what the throw keyword is for; to throw an exception that can be handled in a catch block.
 
Share this answer
 
I like Petes solution best (solution 3), but I find that none of the solutions actually answer the question ("what is the purpose of..."). So here's my own take:

Exceptions are one of several possible ways to report error conditions to the higher levels in a call stack. In general, you should not use exceptions to indicate conditions that are expected in normal use, even if they are such that you cannot continue execution of your function. E. g. if you try to open a specific data file, but cannot find it, you should by all means inform the user of the problem, but this problem does not warrant exception handling. OTOH, if you call a system function and the resulting data is in a format or in a range of values that doesn't match the expectations and shouldn't normally be possible, then it's time to inform the 'higher levels' of a critical problem: that is where you throw() an exception.

In short:
exception is not expectation
or the somewhat more familiar:
expect the unexpected! (or maybe I should turn this into except the unexpected ;) )

Of course, this is somewhat self-defeating: if you don't expect a certain value or condition, then how would you test against it? The answer is to do the opposite: test for the values and conditions that you expect, and treat everything else as an exception!

As pointed out in other responses, when your function throws an exception, any function calling yours (directly or indirectly) should consider catching it. If they don't, the exception will be passed on to even higher levels, until it reaches main(). You should use try/catch in this manner only if you know what to do about the exception. Else you shouldn't bother and leave it to the 'higher-ups'.


Note that there are many people who consider exceptions a mechanic that effectively replaces error codes: they'd argue that you don't need to return error codes for stuff like 'file not found', if you have exceptions that can be (ab)used to the same end. However: exceptions don't come for free, and I don't think the user would find it funny if the application crashed with a message like 'file not found', because noone in QA thought to test for that scenario and none of the programmers of the higher-up functions felt responsible for catching it!

There are certainly similar problems associated with using error codes, but unless the untreated error code somehow causes a nasty problem, at least the application will not crash to desktop, irritating the user.

At least that's my take on it - YMMV
 
Share this answer
 
v2
Comments
Philippe Mori 20-Feb-14 8:39am    
For things like "File not found". it might not be that bad to use an exception provide there is a way to test the existance of a file...
 
Share this answer
 
Almost any line of code can cause an exception, particularly exceptions that are thrown by the common language runtime itself, such as OutOfMemoryException and StackOverflowException. Most applications do not have to deal with these exceptions, but you should be aware of this possibility when writing libraries to be used by others. For suggestions on when to set code in a try block,
The following code example uses a try/catch block to catch a possible exception. The Main method contains a try block with a StreamReader statement that opens a data file called data.txt and writes a string from the file. Following the try block is a catch block that catches any exception that results from the try block.
C#
using namespace System;
using namespace System::IO;

public ref class ProcessFile
{
public:
    static void Main()
    {
        try
        {
            StreamReader^ sr = File::OpenText("data.txt");
            Console::WriteLine("The first line of this file is {0}", sr->ReadLine());
        sr->Close();
        }
        catch (Exception^ e)
        {
            Console::WriteLine("An error occurred: '{0}'", e);
        }
    }
};

int main()
{
    ProcessFile::Main();
}
 
Share this answer
 
Comments
CHill60 12-Apr-14 6:01am    
Wouldn't it have been quicker (and more honest) to just post the link http://msdn.microsoft.com/en-us/library/xtd0s8kd(v=vs.110).aspx[^]
Try Catch blocks are used i exception handling in most of programming languages.
In try block if some thing fails it is handled by catch block so that your application not terminated unexpectedly.
C#
try {
   //some code that can generate exception
catch (Exception ex) {
   //print ex
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900