Handling Errors during the Program Execution Svetlin Nakov Telerik Corporation www.telerik.com.

Slides:



Advertisements
Similar presentations
1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
Advertisements

Error-handling using exceptions
Topics Introduction Types of Errors Exceptions Exception Handling
Error Handling in.NET Exceptions. Error Handling Old way (Win32 API and COM): MyFunction() { error_1 = doSomething(); if (error_1) display error else.
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Try…Catch…Finally Blocks ( continued ) Generic catch clause –Omit argument list with the catch –Any exception thrown is handled by executing code within.
C# Programming: From Problem Analysis to Program Design1 Debugging and Handling Exceptions C# Programming: From Problem Analysis to Program Design 3 rd.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Mahmoud Rafeek Alfarra Computer Programming || Chapter 2: Exception handling.
Chapter 11 Debugging and Handling Exceptions
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
CS 3260 Dennis A. Fairclough Version 1.0
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
Exception Handling An Exception is an indication of a problem that occurs during a program’s execution. Exception handling enables the programmer to create.
Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
 2002 Prentice Hall. All rights reserved. 1 Chapter 11 – Exception Handling Outline 11.1Introduction 11.2 Exception Handling Overview 11.3 Example: DivideByZeroException.
 2002 Prentice Hall. All rights reserved. 1 Chapter 11 – Exception Handling Outline 11.1 Introduction 11.2 Exception Handling Overview 11.3 Example: DivideByZeroException.
 2009 Pearson Education, Inc. All rights reserved Exception Handling.
Reading and Writing to the Console Svetlin Nakov Telerik Corporation
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
 2002 Prentice Hall. All rights reserved. 1 Exception Handling Overview Exception handling –Enable clear, robust and more fault-tolerant programs –Process.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
Handling Errors during the Program Execution Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
Pemrograman VisualMinggu …12… Page 1 MINGGU Ke Duabelas Pemrograman Visual Pokok Bahasan: Exception Handling Tujuan Instruksional Khusus: Mahasiswa dapat.
Exceptions Programming in C# Exceptions CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Exceptions Syntax, semantics, and pragmatics Exceptions1.
How to Design Error Steady Code Ivaylo Bratoev Telerik Corporation
VB.Net - Exceptions Copyright © Martin Schray
10/20/2015Assoc. Prof. Stoyan Bonev1 COS240 O-O Languages AUBG, COS dept Lecture 37 Title: C# vs. Java Exception Handling Reference: COS240 Syllabus.
Introduction to Exception Handling and Defensive Programming.
Defensive Programming, Assertions and Exceptions Designing Fault-Resistant Code SoftUni Team Technical Trainers Software University
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Defensive Programming, Assertions and Exceptions Designing Error Steady Code SoftUni Team Technical Trainers Software University
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception Handling SWE 344 Internet Protocols & Client Server Programming.
C# Exceptions 1 CNS 3260 C#.NET Software Development.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Enhanced Car Payment Calculator Application Introducing Exception Handling.
Lecture 11 Dr. Eng. Ibrahim El-Nahry Exception Handling.
Chapter 11 – Exception Handling
Debugging and Handling Exceptions
Debugging and Handling Exceptions
Advanced Programming Behnam Hatami Fall 2017.
CNS 3260 C# .NET Software Development
Exception Handling Chapter 9.
ATS Application Programming: Java Programming
Exception Handling CSCI293 - C# October 3, 2005.
Part B – Structured Exception Handling
Programming in C# Lesson 5. Exceptions..
Chapter 13 Exception Handling: A Deeper Look
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Handling Errors during the Program Execution Svetlin Nakov Telerik Corporation

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

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

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 or the 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

class ExceptionsTest { 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 caught: {0}\n{1}", Console.Error.WriteLine("Exception caught: {0}\n{1}", fe.Message, fe.StackTrace); fe.Message, fe.StackTrace); } }} 10

 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 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 11

 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: 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) 12

Live Demo

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

 All.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 successors DivideByZeroException and OverflowException try{ // Do some works that can raise an exception // Do some works that can raise an exception} catch (System.ArithmeticException) { // Handle the caught arithmetic exception // Handle the caught arithmetic exception} 17

static void Main(string[] args) { 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 18

 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: 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} 19

 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 error message:  Exceptions can take message and cause:  Note: if the original exception is not passed the initial cause of the exception is lost 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);} 23

 Caught exceptions can be re-thrown again: 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 tha last caught exception throw; // Re-throws tha last caught exception} 24

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

Live Demo

27  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 )

 The construction:  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 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} 29

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

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  Handling all exception disregarding their type is popular bad practice!  When raising an exception always pass to the constructor good explanation message 33

 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.: on invalid user input)  Some exceptions can be thrown at any time with no way to predict them, e.g.: System.OutOfMemoryException 34

 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 other handlers  Unhandled exceptions cause error messages  Try-finally ensures that given code block is always executed (even when an exception is thrown) 35

Questions?

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 invalid number or non-number text is entered, the method should throw an exception. Based on 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. 38