Download presentation
Presentation is loading. Please wait.
Published byGervase Craig Modified over 9 years ago
1
Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University http://softuni.bg
2
2 1.What are Exceptions? 2.Handling Exceptions 3.The System.Exception Class 4.Types of Exceptions and their Hierarchy 5.Raising (Throwing) Exceptions 6.Best Practices 7.Creating Custom Exceptions Table of Contents
3
What are Exceptions? The Paradigm of Exceptions in OOP
4
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?
5
Handling Exceptions Catching and Processing Errors
6
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 // Do some work that can raise an exception} catch (SomeException) { // Handle the caught exception // Handle the caught exception}
7
7 Handling Exceptions – Example static void Main() { string s = Console.ReadLine(); string s = Console.ReadLine(); try try { int.Parse(s); int.Parse(s); Console.WriteLine( Console.WriteLine( "You entered a valid Int32 number {0}.", s); "You entered a valid Int32 number {0}.", s); } catch (FormatException) catch (FormatException) { Console.WriteLine("Invalid integer number!"); Console.WriteLine("Invalid integer number!"); } catch (OverflowException) catch (OverflowException) { Console.WriteLine( Console.WriteLine( "The number is too big to fit in Int32!"); "The number is too big to fit in Int32!"); }}
8
Handling Exceptions Live Demo
9
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
10 Exception Properties – Example class ExceptionsExample { public static void CauseFormatException() public static void CauseFormatException() { { string str = "an invalid number"; string str = "an invalid number"; int.Parse(str); int.Parse(str); } } static void Main() static void Main() { { try try { { CauseFormatException(); CauseFormatException(); } } catch (FormatException fe) catch (FormatException fe) { { Console.Error.WriteLine("Exception: {0}\n{1}", Console.Error.WriteLine("Exception: {0}\n{1}", fe.Message, fe.StackTrace); fe.Message, fe.StackTrace); } } }}
11
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.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s) at System.Int32.Parse(String s) at ExceptionsTest.CauseFormatException() in c:\consoleapplication1\exceptionstest.cs:line 8 at ExceptionsTest.CauseFormatException() in c:\consoleapplication1\exceptionstest.cs:line 8 at ExceptionsTest.Main(String[] args) in c:\consoleapplication1\exceptionstest.cs:line 15 at ExceptionsTest.Main(String[] args) in c:\consoleapplication1\exceptionstest.cs:line 15
12
Exception Properties Live Demo
13
The Hierarchy of Exceptions
14
14 Exceptions in.NET Framework are organized in a hierarchy Exception Hierarchy in.NET
15
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
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 // Do some work that can cause an exception} catch (System.ArithmeticException) { // Handle the caught arithmetic exception // Handle the caught arithmetic exception}
17
17 Find the Mistake! static void Main() { string str = Console.ReadLine(); string str = Console.ReadLine(); try try { Int32.Parse(str); Int32.Parse(str); } catch (Exception) catch (Exception) { Console.WriteLine("Cannot parse the number!"); Console.WriteLine("Cannot parse the number!"); } catch (FormatException) catch (FormatException) { Console.WriteLine("Invalid integer number!"); Console.WriteLine("Invalid integer number!"); } catch (OverflowException) catch (OverflowException) { Console.WriteLine( Console.WriteLine( "The number is too big to fit in Int32!"); "The number is too big to fit in Int32!"); }} This should be last Unreachable code
18
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 // Do some work that can raise any exception}catch{ // Handle the caught exception // Handle the caught exception}
19
Throwing Exceptions
20
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
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 the program 9. Find handler 10. Display error message
22
Call Stack Example Live Demo
23
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); throw new InvalidOperationException("Cannot save invoice.", sqlEx);}
24
24 Caught exceptions can be re-thrown again: Re-Throwing Exceptions try{ Int32.Parse(str); Int32.Parse(str);} catch (FormatException fe) { Console.WriteLine("Parse failed!"); Console.WriteLine("Parse failed!"); throw fe; // Re-throw the caught exception throw fe; // Re-throw the caught exception} catch (FormatException) { throw; // Re-throws the last caught exception throw; // Re-throws the last caught exception}
25
25 Throwing Exceptions – Example public static double Sqrt(double value) { if (value < 0) if (value < 0) throw new System.ArgumentOutOfRangeException("value", throw new System.ArgumentOutOfRangeException("value", "Sqrt for negative numbers is undefined!"); "Sqrt for negative numbers is undefined!"); return Math.Sqrt(value); return Math.Sqrt(value);} static void Main() { try try { Sqrt(-1); Sqrt(-1); } catch (ArgumentOutOfRangeException ex) catch (ArgumentOutOfRangeException ex) { Console.Error.WriteLine("Error: " + ex.Message); Console.Error.WriteLine("Error: " + ex.Message); throw; throw; }}
26
Throwing Exceptions Live Demo
27
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
28
Using Try-Finally Blocks
29
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 // Do some work that can cause an exception}finally{ // This block will always execute // This block will always execute}
30
30 try-finally – Example static void TestTryFinally() { Console.WriteLine("Code executed before try-finally."); Console.WriteLine("Code executed before try-finally."); try try { string str = Console.ReadLine(); string str = Console.ReadLine(); int.Parse(str); int.Parse(str); Console.WriteLine("Parsing was successful."); Console.WriteLine("Parsing was successful."); return; // Exit from the current method return; // Exit from the current method } catch (FormatException) catch (FormatException) { Console.WriteLine("Parsing failed!"); Console.WriteLine("Parsing failed!"); } finally finally { Console.WriteLine("This cleanup code is always executed."); Console.WriteLine("This cleanup code is always executed."); } Console.WriteLine("This code is after the try-finally block."); Console.WriteLine("This code is after the try-finally block.");}
31
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 ( ) { // Use the resource. It will be disposed (closed) at the end // Use the resource. It will be disposed (closed) at the end} Resource resource = AllocateResource(); try { // Use the resource here … // Use the resource here … } finally { if (resource != null) resource.Dispose(); if (resource != null) resource.Dispose();}
32
Try-Finally Live Demo
33
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; int lineNumber = 0; string line = reader.ReadLine(); string line = reader.ReadLine(); while (line != null) while (line != null) { lineNumber++; lineNumber++; Console.WriteLine("Line {0}: {1}", lineNumber, line); Console.WriteLine("Line {0}: {1}", lineNumber, line); line = reader.ReadLine(); line = reader.ReadLine(); }}
34
Reading a Text File Live Demo
35
Exceptions: Best Practices
36
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
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
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
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) public TankException(string msg) : base(msg) : base(msg) { }} throw new TankException("Not enough fuel to travel");
40
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
41
? ? ? ? ? ? ? ? ? OOP – Exception Handling httpshttps://softuni.bg/courses/oop/
42
License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 42 Attribution: this work may contain portions from "OOP" course by Telerik Academy under CC-BY-NC-SA licenseOOPCC-BY-NC-SA
43
Free Trainings @ Software University Software University Foundation – softuni.orgsoftuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity Software University @ YouTube youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bgforum.softuni.bg
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.