Rethrowing exception- JAVA

erajan96 993 views 9 slides Sep 01, 2017
Slide 1
Slide 1 of 9
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9

About This Presentation

Exception Handling, Rethrowing Exception, Try-Catch


Slide Content

Rethrowing Exception and User defined exception Rajan Shah Name:

Exception Exception are of two types: Synchronous exceptions- Errors such as “out-of-range index” and “overflow”. Asynchronous exceptions- Errors that are caused by the events beyond the control of the program. Purpose- to provide means to detect and report an “exceptional circumstance” so that appropriate action can be taken.

Error handling code The error handling code performs the following tasks: Find the problem (Hit the exception), Inform that an error has occurred (Throw the exception), Receive the error info (Catch the exception) and Take corrective action (Handle the exception).

Exception handling mechanism Try: The keyword try is used to preface a block of statements which may generate exceptions. Throw: Exception is thrown using throw statement in try block. Catch: Catches the exception thrown by the throw statement in the try block.

Rethrowing an Exception Rethrowing an expression from within an exception handler can be done by calling throw, by itself, with no exception (without arguments). This causes the current exception to be passed on to an outer try/catch sequence. An exception can only be rethrown from within a catch block. When an exception is rethrown, it is propagated outward to the next catch block.

Rethrowing an Exception #include < iostream > using namespace std; void MyHandler () {    try    {        throw “hello”;    }    catch (const char*)    {     cout <<”Caught exception inside MyHandler \n”;    throw; // rethrow char* out of function    } } int main() {     cout << “Main start”;    try    {         MyHandler ();    }    catch(const char*)    {        cout <<”Caught exception inside Main\n”;    }         cout << “Main end”;        return 0; }

User Defined Exception #include < iostream > #include <exception> using namespace std; struct MyException : public exception { const char * what () const throw () { return "C++ Exception"; } }; int main() { try { throw MyException (); } catch( MyException & e) { std:: cout << " MyException caught" << std:: endl ; std:: cout << e.what () << std:: endl ; } }

User Defined Exception The example shows the use of std::exception class to implement user defined exception. what() -- is a public method provided by exception class and it has been overridden by all the child exception classes. This returns the cause of an exception.

THANK YOU