Handling Errors during the Program Execution Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer www.nakov.com.

Slides:



Advertisements
Similar presentations
Windows Basic and Dynamic Disk Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator Marian Marinov CEO of 1H Ltd.
Advertisements

HTML Forms, GET, POST Methods Tran Anh Tuan Edit from Telerik Academy
Make swiftly iOS development Telerik Academy Telerik Academy Plus.
Amazon S 3, App Engine Blobstore, Google Cloud Storage, Azure Blobs Svetlin Nakov Telerik Software Academy academy.telerik.com.
RPN and Shunting-yard algorithm Ivaylo Kenov Telerik Software Academy academy.telerik.com Technical Assistant
Shortest paths in edge-weighted digraph Krasin Georgiev Technical University of Sofia g.krasin at gmail com Assistant Professor.
Handling Errors during the Program Execution Svetlin Nakov Telerik Corporation
Telerik Software Academy Telerik School Academy.
Asynchronous Programming with C# and WinRT
Touch and Gestures with Xamarin Forms
Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team Telerik Software Academy.
Hybrid or Native?! Doncho Minkov Telerik Software Academy Senior Technical Trainer
Done already for your convenience! Telerik School Academy Unity 2D Game Development.
Processing Sequences of Elements Telerik School Academy C# Fundamentals – Part 1.
C# Fundamentals – Part I
NoSQL Concepts, Redis, MongoDB, CouchDB
The Business Plan and the Business Model Margarita Antonova Volunteer Telerik Academy academy.telerik.com Business System Analyst Telerik Corporation.
What are ADTs, STL Intro, vector, list, queue, stack Learning & Development Team Telerik Software Academy.
Making JavaScript code by template! Learning & Development Team Telerik Software Academy.
Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training Who, What, Why?
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Accessing SQL Server and MySQL – Live Demo Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Processing Matrices and Multidimensional Tables Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Telerik Software Academy ASP.NET Web Forms.
Classical OOP in JavaScript Classes and stuff Telerik Software Academy
Using Selenium for Mobile Web Testing Powered by KendoUI Telerik QA Academy Atanas Georgiev Senior QA Engineer KendoUI Team.
NoSQL Concepts, Redis, MongoDB, CouchDB Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
New features: classes, generators, iterators, etc. Telerik Academy Plus JavaScript.Next.
Creating E/R Diagrams with SQL Server Management Studio and MySQL Workbench Svetlin Nakov Telerik Software Academy Manager Technical.
Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy
Loops, Conditional Statements, Functions Tran Anh Tuan Edit from Telerik Academy
Telerik Software Academy ASP.NET Web Forms.
Private/Public fields, Module, Revealing Module Learning & Development Team Telerik Software Academy.
Building Data-Driven ASP.NET Web Forms Apps Telerik Software Academy ASP.NET Web Forms.
Course Introduction Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
General and reusable solutions to common problems in software design Vasil Dininski Telerik Software Academy academy.telerik.com Intern at Telerik Academy.
Planning and Tracking Software Quality Yordan Dimitrov Telerik Corporation Team Leader, Team Pulse, Team Leader, Team Pulse, Telerik Corporation,
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net.
Pavel Kolev Telerik Software Academy Senior.Net Developer and Trainer
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Doing the Canvas the "easy way"! Learning & Development Telerik Software Academy.
Creating and Running Your First C# Program Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Subroutines in Computer Programming Telerik School Academy C# Fundamentals – Part 1.
Correctly Formatting the Source Code Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Data Types, Primitive Types in C++, Variables – Declaration, Initialization, Scope Telerik Software Academy academy.telerik.com Learning and Development.
The past, the present, the future Learning & Development Team Telerik Software Academy.
Learn to Design Error Steady Code Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2.
Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University
Telerik JavaScript Framework Telerik Software Academy Hybrid Mobile Applications.
Telerik Software Academy Databases.
Polymorphism, Class Hierarchies, Exceptions, Strong Cohesion and Loose Coupling Telerik Software Academy Object-Oriented Programming.
Things start to get serious Telerik Software Academy JavaScript OOP.
Learning & Development Mobile apps for iPhone & iPad.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Implementing Control Logic in C# Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical trainer
Inheritance, Abstraction, Encapsulation, Polymorphism Telerik Software Academy Mobile apps for iPhone & iPad.
Mocking tools for easier unit testing Telerik Software Academy High Quality Code.
What why and how? Telerik School Academy Unity 2D Game Development.
Windows Security Model Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator
Programming in C# Lesson 5. Exceptions..
Presentation transcript:

Handling Errors during the Program Execution Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer

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 2

The Paradigm of Exceptions in OOP

 The exceptions in.NET Framework are 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 4

Catching and Processing Errors

 In C# the exceptions can be handled by the try-catch-finally construction  catch blocks can be used multiple times to process different exception types 6 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 static void Main() { string s = Console.ReadLine(); string s = Console.ReadLine(); try try { Int32.Parse(s); Int32.Parse(s); Console.WriteLine( Console.WriteLine( "You entered valid Int32 number {0}.", s); "You entered 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!"); }}

Live Demo

 Exceptions in.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) 9

10 class ExceptionsExample { public static void CauseFormatException() public static void CauseFormatException() { string s = "an invalid number"; string s = "an invalid number"; Int32.Parse(s); Int32.Parse(s); } 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); } }}

 The Message property gives brief description of the problem  The StackTrace property is extremely useful when identifying the reason caused the exception  The Message property gives brief description of the problem  The StackTrace property is extremely useful when identifying the reason caused the exception 11 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

 File names and line numbers are accessible only if the compilation was in Debug mode  When compiled in Release mode, the information in the property StackTrace is quite different:  File names and line numbers are accessible only if the compilation was in Debug mode  When compiled in Release mode, the information in the property StackTrace is quite different: 12 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 ExceptionsTest.Main(String[] args) at ExceptionsTest.Main(String[] args)

Live Demo

 Exceptions in.NET Framework are organized in a hierarchy 15

.NET exceptions inherit from System.Exception  The system exceptions inherit from System.SystemException, e.g.  System.ArgumentException  System.NullReferenceException  System.OutOfMemoryException  System.StackOverflowException  User-defined exceptions should inherit from System.ApplicationException 16

 When catching an exception of a particular class, all its inheritors (child exceptions) are caught too  Example: Handles ArithmeticException and its descendants DivideByZeroException and OverflowException 17 try{ // Do some works that can cause an exception // Do some works that can cause an exception} catch (System.ArithmeticException) { // Handle the caught arithmetic exception // Handle the caught arithmetic exception}

18 static void Main() { string s = Console.ReadLine(); string s = Console.ReadLine(); try try { Int32.Parse(s); Int32.Parse(s); } catch (Exception) catch (Exception) { Console.WriteLine("Can not parse the number!"); Console.WriteLine("Can not 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

 All exceptions thrown by.NET managed code inherit the System.Exception exception  Unmanaged code can throw other exceptions  For handling all exceptions (even unmanaged) use the construction: 19 try{ // Do some works that can raise any exception // Do some works that can raise any exception}catch{ // Handle the caught exception // Handle the caught exception}

 Exceptions are thrown (raised) by throw keyword in C#  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 suitable catch block is reached to handle it  Unhandled exceptions display error message 21

22 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

 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 23 throw new ArgumentException("Invalid amount!"); try{ Int32.Parse(str); Int32.Parse(str);} catch (FormatException fe) { throw new ArgumentException("Invalid number", fe); throw new ArgumentException("Invalid number", fe);}

 Caught exceptions can be re-thrown again: 24 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 public static double Sqrt(double value) { if (value < 0) if (value < 0) throw new System.ArgumentOutOfRangeException( throw new System.ArgumentOutOfRangeException( "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; }}

Live Demo

 When an invalid parameter 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 ) 27

 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 29 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 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(); Int32.Parse(str); Int32.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( Console.WriteLine( "This cleanup code is always executed."); "This cleanup code is always executed."); } Console.WriteLine( Console.WriteLine( "This code is after the try-finally block."); "This code is after the try-finally block.");}

Live Demo

 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 be left unhandled  Handling all exceptions disregarding their type is popular bad practice (anti-pattern)! 33

 When raising an exception always pass to the constructor good explanation message  When throwing an exception always pass a good description of the problem  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" 34

 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 (e.g. for invalid user input)  CLR could throw exceptions at any time with no way to predict them  E.g. System.OutOfMemoryException 35

 Exceptions provide flexible error handling mechanism in.NET Framework  Allow errors to be handled at multiple levels  Each exception handler processes only errors of 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) 36

форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране

1. Write a program that reads an integer number and calculates and prints its square root. If the number is invalid or negative, print "Invalid number". In all cases finally print "Good bye". Use try-catch-finally. 2. Write a method ReadNumber(int start, int end) that enters an integer number in given range [start…end]. If an invalid number or non-number text is entered, the method should throw an exception. Using this method write a program that enters 10 numbers: a 1, a 2, … a 10, such that 1 < a 1 < … < a 10 <

3. Write a program that enters file name along with its full file path (e.g. C:\WINDOWS\win.ini ), reads its contents and prints it on the console. Find in MSDN how to use System.IO.File.ReadAllText(…). Be sure to catch all possible exceptions and print user- friendly error messages. 4. Write a program that downloads a file from Internet (e.g. and stores it the current directory. Find in Google how to download files in C#. Be sure to catch all exceptions and to free any used resources in the finally block. 39

 “C# Telerik Academy  csharpfundamentals.telerik.com csharpfundamentals.telerik.com  Telerik Software Academy  academy.telerik.com academy.telerik.com  Telerik Facebook  facebook.com/TelerikAcademy facebook.com/TelerikAcademy  Telerik Software Academy Forums  forums.academy.telerik.com forums.academy.telerik.com