Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers...
-
Upload
gervase-craig -
Category
Documents
-
view
247 -
download
0
description
Transcript of Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers...
Exception HandlingHandling Errors Duringthe Program Execution
SoftUni TeamTechnical TrainersSoftware Universityhttp://softuni.bg
OOP
2
1. What are Exceptions?2. Handling Exceptions3. The System.Exception Class4. Types of Exceptions and their Hierarchy5. Raising (Throwing) Exceptions6. Best Practices7. Creating Custom Exceptions
Table of Contents
What are Exceptions?The Paradigm of Exceptions in OOP
4
The exceptions in .NET Framework / Java are a classic implementation of the OOP exception model
Deliver powerful mechanism for centralized handling of errors and unusual events
Substitute procedure-oriented approach, in which each function returns error code
Simplify code construction and maintenance Allow the problematic situations to be processed at multiple
levels
What are Exceptions?
Handling ExceptionsCatching and Processing Errors
6
In C# exceptions can be handled by the try-catch-finally construction
catch blocks can be used multiple times to process different exception types
Handling Exceptions
try{ // Do some work that can raise an exception}catch (SomeException){ // Handle the caught exception}
7
Handling Exceptions – Examplestatic void Main(){ string s = Console.ReadLine(); try { int.Parse(s); Console.WriteLine( "You entered a valid Int32 number {0}.", s); } catch (FormatException) { Console.WriteLine("Invalid integer number!"); } catch (OverflowException) { Console.WriteLine( "The number is too big to fit in Int32!"); }}
Handling ExceptionsLive Demo
9
Exceptions in C# / .NET are objects The System.Exception class is base for all exceptions in
CLR Contains information for the cause of the error / unusual situation
Message – text description of the exception StackTrace – the snapshot of the stack at the moment of
exception throwing InnerException – exception caused the current exception (if
any) Similar concept in Java and PHP
The System.Exception Class
10
Exception Properties – Exampleclass ExceptionsExample{ public static void CauseFormatException() { string str = "an invalid number"; int.Parse(str); } static void Main() { try { CauseFormatException(); } catch (FormatException fe) { Console.Error.WriteLine("Exception: {0}\n{1}", fe.Message, fe.StackTrace); } }}
11
The Message property gives a brief description of the problem The StackTrace property is extremely useful when identifying
the reason that caused the exception
Exception Properties
Exception caught: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s) at ExceptionsTest.CauseFormatException() in c:\consoleapplication1\exceptionstest.cs:line 8 at ExceptionsTest.Main(String[] args) in c:\consoleapplication1\exceptionstest.cs:line 15
Exception PropertiesLive Demo
The Hierarchy of Exceptions
14
Exceptions in .NET Framework are organized in a hierarchy
Exception Hierarchy in .NET
System.Exception
System.SystemException System.ApplicationException
System.NullReferenceException System.FormatException
System.ArithmeticException
System.DivideByZeroException System.OverflowException
SofiaUniversity.InvalidStudentException
15
.NET exceptions inherit from System.Exception The system exceptions inherit from System.SystemException
System.ArgumentException System.FormatException System.NullReferenceException System.OutOfMemoryException System.StackOverflowException
User-defined exceptions should inherit from System.Exception
Types of Exceptions
16
When catching an exception of a particular class, all its inheritors (child exceptions) are caught too, e.g.
Handles ArithmeticException and its descendants DivideByZeroException and OverflowException
Handling Exceptions
try{ // Do some work that can cause an exception}catch (System.ArithmeticException){ // Handle the caught arithmetic exception}
17
Find the Mistake!static void Main(){ string str = Console.ReadLine(); try { Int32.Parse(str); } catch (Exception) { Console.WriteLine("Cannot parse the number!"); } catch (FormatException) { Console.WriteLine("Invalid integer number!"); } catch (OverflowException) { Console.WriteLine( "The number is too big to fit in Int32!"); }}
This should be last
Unreachable code
Unreachable code
18
All exceptions thrown by .NET managed code inherit the System.Exception class
Unmanaged code can throw other exceptions For handling all exceptions (even unmanaged) use the construction:
Handling All Exceptions
try{ // Do some work that can raise any exception}catch{ // Handle the caught exception}
Throwing Exceptions
20
Exceptions are thrown (raised) by the throw keyword Used to notify the calling code in case of error or unusual situation When an exception is thrown:
The program execution stops The exception travels over the stack
Until a matching catch block is reached to handle it Unhandled exceptions display an error message
Throwing Exceptions
21
How Do Exceptions Work?
Main()
Method 1
Method 2
Method N
2. Method call
3. Method call
4. Method call…
Main()
Method 1
Method 2
Method N
8. Find handler
7. Find handler
6. Find handler…
5. Throw an exception
.NET CLR
1. Execute theprogram 9. Find handler
10. Display error message
Call Stack ExampleLive Demo
23
Throwing an exception with an error message:
Exceptions can accept message and cause:
Note: if the original exception is not passed, the initial cause of the exception is lost
Using throw Keyword
throw new ArgumentException("Invalid amount!");
try{ …}catch (SqlException sqlEx){ throw new InvalidOperationException("Cannot save invoice.", sqlEx);}
24
Caught exceptions can be re-thrown again:
Re-Throwing Exceptions
try{ Int32.Parse(str);}catch (FormatException fe){ Console.WriteLine("Parse failed!"); throw fe; // Re-throw the caught exception}
catch (FormatException){ throw; // Re-throws the last caught exception}
25
Throwing Exceptions – Examplepublic static double Sqrt(double value){ if (value < 0) throw new System.ArgumentOutOfRangeException("value", "Sqrt for negative numbers is undefined!"); return Math.Sqrt(value);}static void Main(){ try { Sqrt(-1); } catch (ArgumentOutOfRangeException ex) { Console.Error.WriteLine("Error: " + ex.Message); throw; }}
Throwing ExceptionsLive Demo
27
When an invalid parameter value is passed to a method: ArgumentException, ArgumentNullException, ArgumentOutOfRangeException
When requested operation is not supported NotSupportedException
When a method is still not implemented NotImplementedException
If no suitable standard exception class is available Create own exception class (inherit Exception)
Choosing the Exception Type
Using Try-Finally Blocks
29
The statement:
Ensures execution of given block in all cases When exception is raised or not in the try block
Used for execution of cleaning-up code, e.g. releasing resources
The try-finally Statement
try{ // Do some work that can cause an exception}finally{ // This block will always execute}
30
try-finally – Examplestatic void TestTryFinally(){ Console.WriteLine("Code executed before try-finally."); try { string str = Console.ReadLine(); int.Parse(str); Console.WriteLine("Parsing was successful."); return; // Exit from the current method } catch (FormatException) { Console.WriteLine("Parsing failed!"); } finally { Console.WriteLine("This cleanup code is always executed."); } Console.WriteLine("This code is after the try-finally block.");}
31
In programming we often use the "Dispose" pattern It ensures that resources are always closed properly
The same can be achieved by the "using" keyword in C#:
The "using" Statement
using (<resource>) { // Use the resource. It will be disposed (closed) at the end}
Resource resource = AllocateResource();try { // Use the resource here …} finally { if (resource != null) resource.Dispose();}
Try-FinallyLive Demo
33
Read and display a text file line by line:
Reading a Text File – Example
StreamReader reader = new StreamReader("somefile.txt");using (reader){ int lineNumber = 0; string line = reader.ReadLine(); while (line != null) { lineNumber++; Console.WriteLine("Line {0}: {1}", lineNumber, line); line = reader.ReadLine(); }}
Reading a Text FileLive Demo
Exceptions: Best Practices
36
catch blocks should begin with the exceptions lowest in the hierarchy And continue with the more general exceptions Otherwise a compilation error will occur
Each catch block should handle only these exceptions which it expects If a method is not competent to handle an exception, it should leave it
unhandled Handling all exceptions disregarding their type is a popular bad
practice (anti-pattern)!
Exceptions – Best Practices
37
When raising an exception always pass to the constructor good explanation message
When throwing an exception always pass a good description of the problem The exception message should explain what causes the problem and
how to solve it Good: "Size should be integer in range [1…15]" Good: "Invalid state. First call Initialize()" Bad: "Unexpected error" Bad: "Invalid argument"
Exceptions – Best Practices (2)
38
Exceptions can decrease the application performance Throw exceptions only in situations which are really exceptional
and should be handled Do not throw exceptions in the normal program control flow CLR could throw exceptions at any time with no way to predict
them E.g. System.OutOfMemoryException
Exceptions – Best Practices (3)
39
Custom exceptions inherit an exception class (commonly System.Exception)
Are thrown just like any other exception
Creating Custom Exceptions
public class TankException : Exception{ public TankException(string msg) : base(msg) { }}
throw new TankException("Not enough fuel to travel");
40
Exceptions provide a flexible error handling mechanism Allow errors to be handled at multiple levels Each exception handler processes only errors
of a particular type (and its child types) Other types of errors are processed by some
other handlers later Unhandled exceptions cause error messages
Try-finally ensures given code block is always executed (even when an exception is thrown)
Summary
?
??
?
?
??
?
?
Questions?
OOP – Exception Handling
httpshttps://softuni.bg/courses/oop/
License This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International" license
42
Attribution: this work may contain portions from "OOP" course by Telerik Academy under CC-BY-NC-SA license
Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education,
Profession and Job for Software Developers softuni.bg
Software University @ Facebook facebook.com/SoftwareUniversity
Software University @ YouTube youtube.com/SoftwareUniversity
Software University Forums – forum.softuni.bg