SlideShare a Scribd company logo
Exception Handling
Handling Errors During
the Program Execution
SoftUni Team
Technical Trainers
Software University
http://softuni.bg
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
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 Exceptions
Catching 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 – Example
static 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 Exceptions
Live 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 – Example
class 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:consoleapplication1exceptionstest.cs:line 8
at ExceptionsTest.Main(String[] args) in
c:consoleapplication1exceptionstest.cs:line 15
Exception Properties
Live Demo
The Hierarchy of Exceptions
14
 Exceptions in .NET Framework are organized in a hierarchy
Exception Hierarchy in .NET
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
Call Stack Example
Live 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 – Example
public 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 Exceptions
Live 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 – Example
static 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-Finally
Live 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 File
Live 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
?
OOP – Exception Handling
https://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

More Related Content

PPTX
09. Methods
PPTX
10. Recursion
PPTX
09. Java Methods
PPTX
06.Loops
PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
PPTX
12. Java Exceptions and error handling
PPTX
05. Conditional Statements
PPTX
04. Console Input Output
09. Methods
10. Recursion
09. Java Methods
06.Loops
03 and 04 .Operators, Expressions, working with the console and conditional s...
12. Java Exceptions and error handling
05. Conditional Statements
04. Console Input Output

What's hot (20)

PPTX
03. Operators Expressions and statements
PPTX
13 Strings and Text Processing
PPTX
02. Primitive Data Types and Variables
PPTX
02. Data Types and variables
PPTX
Chapter 22. Lambda Expressions and LINQ
PPTX
05. Java Loops Methods and Classes
PPTX
13. Java text processing
PPTX
Java Tutorial: Part 1. Getting Started
PPT
conditional statements
PPTX
Python programming workshop session 2
PPT
Parameters
PPTX
19. Data Structures and Algorithm Complexity
PPTX
Python programming workshop session 3
PPTX
Python programming workshop session 1
PPT
Java basic tutorial by sanjeevini india
PPTX
Python workshop session 6
PPTX
GE8151 Problem Solving and Python Programming
PPT
C++ Language
PPTX
11. Java Objects and classes
DOCX
Python unit 3 and Unit 4
03. Operators Expressions and statements
13 Strings and Text Processing
02. Primitive Data Types and Variables
02. Data Types and variables
Chapter 22. Lambda Expressions and LINQ
05. Java Loops Methods and Classes
13. Java text processing
Java Tutorial: Part 1. Getting Started
conditional statements
Python programming workshop session 2
Parameters
19. Data Structures and Algorithm Complexity
Python programming workshop session 3
Python programming workshop session 1
Java basic tutorial by sanjeevini india
Python workshop session 6
GE8151 Problem Solving and Python Programming
C++ Language
11. Java Objects and classes
Python unit 3 and Unit 4
Ad

Similar to 12. Exception Handling (20)

PPTX
Exception Handlin g C#.pptx
PDF
Exception Handling.pdf
PPT
Exceptions
PPTX
Exceptions overview
PPT
JP ASSIGNMENT SERIES PPT.ppt
PPTX
Java exception handling
PDF
Java unit3
PDF
Exception Handling notes in java exception
DOCX
Exception handling in java
PPT
Exceptions
PPTX
17 exceptions
PPT
Exception handling in java
PPTX
Java-Exception Handling Presentation. 2024
PPTX
Exception Handling In Java Presentation. 2024
PPTX
java exception.pptx
PPTX
Z blue exception
PPT
Comp102 lec 10
PPTX
Exception Handling
PPT
Exception Handling
PPT
Exception handling and templates
Exception Handlin g C#.pptx
Exception Handling.pdf
Exceptions
Exceptions overview
JP ASSIGNMENT SERIES PPT.ppt
Java exception handling
Java unit3
Exception Handling notes in java exception
Exception handling in java
Exceptions
17 exceptions
Exception handling in java
Java-Exception Handling Presentation. 2024
Exception Handling In Java Presentation. 2024
java exception.pptx
Z blue exception
Comp102 lec 10
Exception Handling
Exception Handling
Exception handling and templates
Ad

More from Intro C# Book (20)

PPTX
17. Java data structures trees representation and traversal
PPTX
Java Problem solving
PPTX
21. Java High Quality Programming Code
PPTX
20.5 Java polymorphism
PPTX
20.4 Java interfaces and abstraction
PPTX
20.3 Java encapsulation
PPTX
20.2 Java inheritance
PPTX
20.1 Java working with abstraction
PPTX
19. Java data structures algorithms and complexity
PPTX
18. Java associative arrays
PPTX
16. Java stacks and queues
PPTX
14. Java defining classes
PPTX
07. Java Array, Set and Maps
PPTX
01. Introduction to programming with java
PPTX
23. Methodology of Problem Solving
PPTX
21. High-Quality Programming Code
PPTX
18. Dictionaries, Hash-Tables and Set
PPTX
16. Arrays Lists Stacks Queues
PPTX
17. Trees and Tree Like Structures
PPTX
15. Streams Files and Directories
17. Java data structures trees representation and traversal
Java Problem solving
21. Java High Quality Programming Code
20.5 Java polymorphism
20.4 Java interfaces and abstraction
20.3 Java encapsulation
20.2 Java inheritance
20.1 Java working with abstraction
19. Java data structures algorithms and complexity
18. Java associative arrays
16. Java stacks and queues
14. Java defining classes
07. Java Array, Set and Maps
01. Introduction to programming with java
23. Methodology of Problem Solving
21. High-Quality Programming Code
18. Dictionaries, Hash-Tables and Set
16. Arrays Lists Stacks Queues
17. Trees and Tree Like Structures
15. Streams Files and Directories

Recently uploaded (20)

PDF
Smart Home Technology for Health Monitoring (www.kiu.ac.ug)
PPT
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
PPTX
newyork.pptxirantrafgshenepalchinachinane
PDF
FINAL CALL-6th International Conference on Networks & IOT (NeTIOT 2025)
PPTX
1402_iCSC_-_RESTful_Web_APIs_--_Josef_Hammer.pptx
PPTX
Database Information System - Management Information System
PDF
Uptota Investor Deck - Where Africa Meets Blockchain
PDF
SlidesGDGoCxRAIS about Google Dialogflow and NotebookLM.pdf
PPTX
Internet Safety for Seniors presentation
PPTX
artificial intelligence overview of it and more
PDF
si manuel quezon at mga nagawa sa bansang pilipinas
PPTX
IPCNA VIRTUAL CLASSES INTERMEDIATE 6 PROJECT.pptx
PDF
Introduction to the IoT system, how the IoT system works
PPTX
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
PDF
Session 1 (Week 1)fghjmgfdsfgthyjkhfdsadfghjkhgfdsa
PDF
📍 LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1 TERPOPULER DI INDONESIA ! 🌟
PPTX
t_and_OpenAI_Combined_two_pressentations
PPT
FIRE PREVENTION AND CONTROL PLAN- LUS.FM.MQ.OM.UTM.PLN.00014.ppt
PDF
The Ikigai Template _ Recalibrate How You Spend Your Time.pdf
PPTX
E -tech empowerment technologies PowerPoint
Smart Home Technology for Health Monitoring (www.kiu.ac.ug)
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
newyork.pptxirantrafgshenepalchinachinane
FINAL CALL-6th International Conference on Networks & IOT (NeTIOT 2025)
1402_iCSC_-_RESTful_Web_APIs_--_Josef_Hammer.pptx
Database Information System - Management Information System
Uptota Investor Deck - Where Africa Meets Blockchain
SlidesGDGoCxRAIS about Google Dialogflow and NotebookLM.pdf
Internet Safety for Seniors presentation
artificial intelligence overview of it and more
si manuel quezon at mga nagawa sa bansang pilipinas
IPCNA VIRTUAL CLASSES INTERMEDIATE 6 PROJECT.pptx
Introduction to the IoT system, how the IoT system works
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
Session 1 (Week 1)fghjmgfdsfgthyjkhfdsadfghjkhgfdsa
📍 LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1 TERPOPULER DI INDONESIA ! 🌟
t_and_OpenAI_Combined_two_pressentations
FIRE PREVENTION AND CONTROL PLAN- LUS.FM.MQ.OM.UTM.PLN.00014.ppt
The Ikigai Template _ Recalibrate How You Spend Your Time.pdf
E -tech empowerment technologies PowerPoint

12. Exception Handling

  • 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?
  • 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 } catch (SomeException) { // Handle the caught exception }
  • 7. 7 Handling Exceptions – Example static 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!"); } }
  • 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() { 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. 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:consoleapplication1exceptionstest.cs:line 8 at ExceptionsTest.Main(String[] args) in c:consoleapplication1exceptionstest.cs:line 15
  • 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 } catch (System.ArithmeticException) { // Handle the caught arithmetic exception }
  • 17. 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. 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 }
  • 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
  • 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); }
  • 24. 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. 25 Throwing Exceptions – Example public 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; } }
  • 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
  • 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 } finally { // This block will always execute }
  • 30. 30 try-finally – Example static 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. 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(); }
  • 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; string line = reader.ReadLine(); while (line != null) { lineNumber++; Console.WriteLine("Line {0}: {1}", lineNumber, line); line = reader.ReadLine(); } }
  • 34. Reading a Text File Live Demo
  • 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) : 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 https://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" license 42  Attribution: this work may contain portions from  "OOP" course by Telerik Academy under CC-BY-NC-SA license
  • 43. 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

Editor's Notes

  • #3: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #4: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #5: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #6: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #7: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #9: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #12: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #13: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #14: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #15: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #16: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #17: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #18: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #19: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #20: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #21: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #23: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #24: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #25: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #26: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #27: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #29: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #30: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #31: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #33: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #35: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #36: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #37: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #39: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*