SlideShare uma empresa Scribd logo
1 de 40
Effective .NET Framework based Development:  Exception Handing and Memory Management Brad Abrams Lead Program Manager Common Language Runtime Team Microsoft Corporation  [email_address]   http:// blogs.msdn.com /brada
Agenda ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Exception Handling Questions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
When to Throw? ,[object Object],[object Object],[object Object],[object Object],[object Object]
What to throw? ,[object Object],[object Object],try {   //some operation } catch (FileNotFoundException fe) {   //do some set of work } catch (DriveNotFoundException be) {   //do some other set of work }
Throwing an Exception ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Performance ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Performance (continued) int i; try {   i = Int32.Parse(“123”); }  catch (FormatException ) {   Console.WriteLine (“Invalid”); } int i; if (!Int32.TryParse (“123”, out i)) {   Console.Writeline(“Invalid”); }
Managing Resources ,[object Object],[object Object],[object Object]
Managing Resources ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],try { . . . } catch (DivisionByZeroException e) {   // do clean up work   throw new BetterException (message, e); }
Catching Exceptions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Catching Exceptions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
catch (Exception e) is your friend ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Agenda ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Memory Management ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Resource Management  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Finalizers ,[object Object],[object Object],public class Resource { ~Resource() { ... } } public class Resource { protected override void Finalize() { try { ... } finally { base.Finalize(); } } }
Finalizers (2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Finalizers (3) ,[object Object],[object Object],[object Object],[object Object],[object Object]
Dispose Pattern ,[object Object],[object Object],[object Object],[object Object],[object Object]
Dispose Pattern (2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Implementing IDisposable public class Resource: IDisposable { private bool disposed = false; pubic int GetValue () {   if (disposed) throw new ObjectDisposedException(); // do work } public void Dispose() { if (disposed) return; Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { // Dispose dependent objects disposed = true; } // Free unmanaged resources } ~Resource() { Dispose(false); } }
Using Statement ,[object Object],[object Object],[object Object],using (Resource res = new Resource()) { res.DoWork(); } Resource res = new Resource(...); try { res.DoWork(); } finally { if (res != null)  ((IDisposable)res).Dispose(); }
Using Statement ,[object Object],[object Object],[object Object],Using res As Resource = New Resource   () res.DoWork() End Using Dim res As New Resource() Try res.DoWork() Finally If res IsNot Nothing Then CType(res, IDisposable).Dispose() End If End Try VB 2005
Using Statement (2) ,[object Object],[object Object],static void Copy(string sourceName, string destName) { Stream input = File.OpenRead(sourceName); Stream output = File.Create(destName); byte[] b = new byte[65536]; int n; while ((n = input.Read(b, 0, b.Length)) != 0) { output.Write(b, 0, n); } output.Close(); input.Close(); }
Using Statement (3) static void Copy(string sourceName, string destName)   { Stream input = File.OpenRead(sourceName); Stream output = File.Create(destName); try   { byte[] b = new byte[65536]; int n; while ((n = input.Read(b, 0, b.Length)) != 0)   { output.Write(b, 0, n); } } finally   { output.Close(); input.Close(); } }
Using Statement (4) static void Copy(string sourceName, string destName) { Stream input = File.OpenRead(sourceName); try { Stream output = File.Create(destName); try { byte[] b = new byte[65536]; int n; while ((n = input.Read(b, 0, b.Length)) != 0) { output.Write(b, 0, n); } } finally { output.Close(); } } finally { input.Close(); } }
Using Statement (4) ,[object Object],[object Object],static void Copy(string sourceName, string destName) { using (Stream input = File.OpenRead(sourceName)) using (Stream output = File.Create(destName)) { byte[] b = new byte[65536]; int n; while ((n = input.Read(b, 0, b.Length)) != 0) { output.Write(b, 0, n); } } }
Resource Management  2.0 Feature: MemoryPressure ,[object Object],[object Object],[object Object],[object Object]
Resource Management  2.0 Feature: MemoryPressure class Bitmap { private long _size; Bitmap (string path ) {   _size = new FileInfo(path).Length;   GC.AddMemoryPressure(_size);   // other work } ~Bitmap() {   GC.RemoveMemoryPressure(_size);   // other work } }
Resource Management  2.0 Feature: HandleCollector ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],HandleCollector(string name, int initialThreshold,    int maximumThreshold);
Resource Management  2.0 Feature: HandleCollector static readonly HandleCollector GdiHandleType =  new HandleCollector( “GdiHandles”, 10, 50); static IntPtr CreateSolidBrush() { IntPtr temp = CreateSolidBrushImpl(…); GdiHandleType.Add(); return temp; } internal static void DeleteObject(IntPtr handle) { DeleteObjectImpl(handle); GdiHandleType.Remove(); }
More Information ,[object Object],The SLAR Designing .NET Class Libraries:  http://msdn.microsoft.com/netframework/programming/classlibraries/   FxCop is your ally in the fight:  http://www.gotdotnet.com/team/fxcop/   .NET Framework Resource Management  whitepaper Resource Management with the CLR: The IDisposable Pattern  Special thanks to  Brian Harry  for significant input in the exceptions section Applied Microsoft .NET Framework Programming
Back up
Intro to Exception Handling in VB ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
On Error vs. Try/Catch/Finally Try '<code that may fail> Catch  ex  As  Exception '<error handling code> Finally '<clean up> End Try fReRaise =  False OnError GoTo  ErrHandler '<code that may fail> GoTo  CleanUp ErrHandler: If  '<condition we can handle>   Then '<error handling code> Else fReRaise =  True End If CleanUp: If  fReRaise  Then  Err.Raise errNum OnError GoTo  ErrHandler '<code that may fail> ErrHandler: If  '<condition we can handle>   Then '<error handling code> fReRaise =  False Try '<code that may fail> Else fReRaise =  True End If CleanUp: If  fReRaise  Then  Err.Raise errNum Catch  ex  As  Exception '<error handling code> Finally '<clean up>
VB 2005 Exception Support ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Using Exceptions: Creating new Exceptions (continued) ,[object Object],public class XxxException : YyyException {   public XxxException () {}   public   XxxException (string message) {}   public   XxxException (string message,  Exception inner) {}   protected   XxxException ( SerializationInfo info, StreamingContext context) {} } ,[object Object]
Using Exceptions: Bad Practice ,[object Object],[object Object],public class ArgumentNullException :    ArgumentException {   public ArgumentNullException   () {}  public   ArgumentNullException   (string paramName) {}  public   ArgumentNullException   (string paramName,   string message) {} }
Using Exceptions: Bad Practice ,[object Object],throw new ArgumentNullException (&quot;the value must   pass an employee name&quot;); throw new ArgumentNullException (&quot;Name&quot;, &quot;the value   must pass an employee name&quot;); Unhandled Exception: System.ArgumentNullException: Value cannot be null. Parameter name: the value must pass an employee name ,[object Object],[object Object],[object Object]

Mais conteúdo relacionado

Mais procurados

L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handlingteach4uin
 
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016Christian Schneider
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handlingraksharao
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Exploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaExploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaCODE WHITE GmbH
 
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...Christopher Frohoff
 
Exceptionhandling
ExceptionhandlingExceptionhandling
ExceptionhandlingNuha Noor
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handlingDeepak Sharma
 
Ln monitoring repositories
Ln monitoring repositoriesLn monitoring repositories
Ln monitoring repositoriessnyff
 
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Christian Schneider
 
Decompiling Java - SCAM2009 Presentation
Decompiling Java - SCAM2009 PresentationDecompiling Java - SCAM2009 Presentation
Decompiling Java - SCAM2009 PresentationJames Hamilton
 
Black Hat EU 2010 - Attacking Java Serialized Communication
Black Hat EU 2010 - Attacking Java Serialized CommunicationBlack Hat EU 2010 - Attacking Java Serialized Communication
Black Hat EU 2010 - Attacking Java Serialized Communicationmsaindane
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception HandlingLemi Orhan Ergin
 

Mais procurados (20)

Exceptions handling notes in JAVA
Exceptions handling notes in JAVAExceptions handling notes in JAVA
Exceptions handling notes in JAVA
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Java exception
Java exception Java exception
Java exception
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Java review: try catch
Java review: try catchJava review: try catch
Java review: try catch
 
Exploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaExploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in Java
 
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
 
Chapter 7
Chapter 7Chapter 7
Chapter 7
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Ln monitoring repositories
Ln monitoring repositoriesLn monitoring repositories
Ln monitoring repositories
 
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
 
Decompiling Java - SCAM2009 Presentation
Decompiling Java - SCAM2009 PresentationDecompiling Java - SCAM2009 Presentation
Decompiling Java - SCAM2009 Presentation
 
Black Hat EU 2010 - Attacking Java Serialized Communication
Black Hat EU 2010 - Attacking Java Serialized CommunicationBlack Hat EU 2010 - Attacking Java Serialized Communication
Black Hat EU 2010 - Attacking Java Serialized Communication
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
 

Semelhante a CLR Exception Handing And Memory Management

Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
Perfomatix - Java Coding Standards
Perfomatix - Java Coding StandardsPerfomatix - Java Coding Standards
Perfomatix - Java Coding StandardsPerfomatix Solutions
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz SAurabh PRajapati
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...yazad dumasia
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Groupbrada
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.pptAjit Mali
 
Exception handling
Exception handlingException handling
Exception handlingRaja Sekhar
 
Back-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldBack-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldDavid McCarter
 
Back-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldBack-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldDavid McCarter
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011YoungSu Son
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Framework Design Guidelines
Framework Design GuidelinesFramework Design Guidelines
Framework Design GuidelinesMohamed Meligy
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014Matthias Noback
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)David McCarter
 
Android | Busy Java Developers Guide to Android: Persistence | Ted Neward
Android | Busy Java Developers Guide to Android: Persistence | Ted NewardAndroid | Busy Java Developers Guide to Android: Persistence | Ted Neward
Android | Busy Java Developers Guide to Android: Persistence | Ted NewardJAX London
 

Semelhante a CLR Exception Handing And Memory Management (20)

Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Perfomatix - Java Coding Standards
Perfomatix - Java Coding StandardsPerfomatix - Java Coding Standards
Perfomatix - Java Coding Standards
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Group
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.ppt
 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Exception handling
Exception handlingException handling
Exception handling
 
Back-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldBack-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real World
 
Back-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldBack-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real World
 
Intake 37 5
Intake 37 5Intake 37 5
Intake 37 5
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Framework Design Guidelines
Framework Design GuidelinesFramework Design Guidelines
Framework Design Guidelines
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014
 
EnScript Workshop
EnScript WorkshopEnScript Workshop
EnScript Workshop
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
Android | Busy Java Developers Guide to Android: Persistence | Ted Neward
Android | Busy Java Developers Guide to Android: Persistence | Ted NewardAndroid | Busy Java Developers Guide to Android: Persistence | Ted Neward
Android | Busy Java Developers Guide to Android: Persistence | Ted Neward
 

Último

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 

CLR Exception Handing And Memory Management

  • 1. Effective .NET Framework based Development: Exception Handing and Memory Management Brad Abrams Lead Program Manager Common Language Runtime Team Microsoft Corporation [email_address] http:// blogs.msdn.com /brada
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8. Performance (continued) int i; try { i = Int32.Parse(“123”); } catch (FormatException ) { Console.WriteLine (“Invalid”); } int i; if (!Int32.TryParse (“123”, out i)) { Console.Writeline(“Invalid”); }
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22. Implementing IDisposable public class Resource: IDisposable { private bool disposed = false; pubic int GetValue () { if (disposed) throw new ObjectDisposedException(); // do work } public void Dispose() { if (disposed) return; Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { // Dispose dependent objects disposed = true; } // Free unmanaged resources } ~Resource() { Dispose(false); } }
  • 23.
  • 24.
  • 25.
  • 26. Using Statement (3) static void Copy(string sourceName, string destName) { Stream input = File.OpenRead(sourceName); Stream output = File.Create(destName); try { byte[] b = new byte[65536]; int n; while ((n = input.Read(b, 0, b.Length)) != 0) { output.Write(b, 0, n); } } finally { output.Close(); input.Close(); } }
  • 27. Using Statement (4) static void Copy(string sourceName, string destName) { Stream input = File.OpenRead(sourceName); try { Stream output = File.Create(destName); try { byte[] b = new byte[65536]; int n; while ((n = input.Read(b, 0, b.Length)) != 0) { output.Write(b, 0, n); } } finally { output.Close(); } } finally { input.Close(); } }
  • 28.
  • 29.
  • 30. Resource Management 2.0 Feature: MemoryPressure class Bitmap { private long _size; Bitmap (string path ) { _size = new FileInfo(path).Length; GC.AddMemoryPressure(_size); // other work } ~Bitmap() { GC.RemoveMemoryPressure(_size); // other work } }
  • 31.
  • 32. Resource Management 2.0 Feature: HandleCollector static readonly HandleCollector GdiHandleType = new HandleCollector( “GdiHandles”, 10, 50); static IntPtr CreateSolidBrush() { IntPtr temp = CreateSolidBrushImpl(…); GdiHandleType.Add(); return temp; } internal static void DeleteObject(IntPtr handle) { DeleteObjectImpl(handle); GdiHandleType.Remove(); }
  • 33.
  • 35.
  • 36. On Error vs. Try/Catch/Finally Try '<code that may fail> Catch ex As Exception '<error handling code> Finally '<clean up> End Try fReRaise = False OnError GoTo ErrHandler '<code that may fail> GoTo CleanUp ErrHandler: If '<condition we can handle> Then '<error handling code> Else fReRaise = True End If CleanUp: If fReRaise Then Err.Raise errNum OnError GoTo ErrHandler '<code that may fail> ErrHandler: If '<condition we can handle> Then '<error handling code> fReRaise = False Try '<code that may fail> Else fReRaise = True End If CleanUp: If fReRaise Then Err.Raise errNum Catch ex As Exception '<error handling code> Finally '<clean up>
  • 37.
  • 38.
  • 39.
  • 40.