exception handling handling errors during the program execution softuni team technical trainers...

43
Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University http:// softuni.bg OOP

Upload: gervase-craig

Post on 06-Jan-2018

249 views

Category:

Documents


0 download

DESCRIPTION

What are Exceptions? The Paradigm of Exceptions in OOP

TRANSCRIPT

Page 1: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

Exception HandlingHandling Errors Duringthe Program Execution

SoftUni TeamTechnical TrainersSoftware Universityhttp://softuni.bg

OOP

Page 2: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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

Page 3: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

What are Exceptions?The Paradigm of Exceptions in OOP

Page 4: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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?

Page 5: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

Handling ExceptionsCatching and Processing Errors

Page 6: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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}

Page 7: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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!"); }}

Page 8: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

Handling ExceptionsLive Demo

Page 9: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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

Page 10: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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); } }}

Page 11: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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

Page 12: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

Exception PropertiesLive Demo

Page 13: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

The Hierarchy of Exceptions

Page 14: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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

Page 15: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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

Page 16: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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}

Page 17: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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

Page 18: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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}

Page 19: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

Throwing Exceptions

Page 20: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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

Page 21: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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

Page 22: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

Call Stack ExampleLive Demo

Page 23: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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);}

Page 24: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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}

Page 25: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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; }}

Page 26: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

Throwing ExceptionsLive Demo

Page 27: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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

Page 28: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

Using Try-Finally Blocks

Page 29: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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}

Page 30: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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.");}

Page 31: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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();}

Page 32: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

Try-FinallyLive Demo

Page 33: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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(); }}

Page 34: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

Reading a Text FileLive Demo

Page 35: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

Exceptions: Best Practices

Page 36: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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

Page 37: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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)

Page 38: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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)

Page 39: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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");

Page 40: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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

Page 42: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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

Page 43: Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University

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