📘 C# Blog Series – Blog 43 **“C# Exception Handling — Server को Crash होने से कैसे बचाते हैं?

📘 C# Blog Series – Blog 43

**“C# Exception Handling — Server को Crash होने से कैसे बचाते हैं?





(Real-Life Example: Try–Catch Patterns, Global Exception Handler, Logging, GPS Server Fail-Safe)”**

जब आप GPS Tracking Server, API Backend, Billing System या कोई भी real-time system बनाते हो—
Crash = सबसे बड़ा खतरा

C# में Exception Handling आपको allow करता है:

✔ Error को पकड़ना
✔ Server को बचाना
✔ Logs write करना
✔ Auto recovery
✔ User को clean response देना

आज हम सीखेंगे:

  • Try–catch का सही उपयोग

  • Finally block

  • Custom exceptions

  • Logging

  • Global exception handling

  • GPS server में fail-safe design


🟦 1. Exception क्या है? (Simple Definition)

Exception =
वो error जो runtime पर program को रोक देती है।

Examples:

  • Divide by zero

  • Null reference

  • File not found

  • Network timeout

  • Database failure

अगर पकड़ नहीं पाओ →
System crash।


🟢 2. Try–Catch Basics

try { int a = 10 / 0; } catch(Exception ex) { Console.WriteLine(ex.Message); }

Program crash नहीं होगा।


3. Finally — हमेशा execute होता है

इसका use resource cleanup में होता है:

try { stream.Read(buffer); } catch(Exception ex) { Log(ex); } finally { stream.Close(); // हमेशा चलेगा }

GPS server में stream/file cleanup MOST important है।


🌟 4. Real GPS Example: Packet Parsing Fail-Safe

try { parser.Parse(packet, device); } catch(Exception ex) { File.AppendAllText("errors.log", ex + "\n"); }

अब corrupt packet पूरे server को crash नहीं करेगा।


🟠 5. Specific Exceptions पकड़ना (Best Practice)

❌ Bad:

catch(Exception ex)

✔ Good:

catch(FormatException ex) catch(NullReferenceException ex) catch(TimeoutException ex)

Specific catches से debugging आसान होती है।


🔵 6. Multiple Catch Blocks Example

try { ProcessPacket(pkt); } catch(FormatException ex) { Log("Packet format error"); } catch(IOException ex) { Log("File IO error"); } catch(Exception ex) { Log("Unknown error"); }

🟣 7. Custom Exception (Professional GPS Server Feature)

Define:

class PacketFormatException : Exception { public PacketFormatException(string msg) : base(msg) { } }

Use:

if(!pkt.Contains(",")) throw new PacketFormatException("Invalid GPS packet");

यह advanced debugging में बहुत helpful होता है।


🔥 8. Real-Life GPS Server: Unknown Packet Dump + Exception

catch(PacketFormatException ex) { File.AppendAllText("dump_unknown.log", packet + "\n"); }

अब unknown packets future debugging के लिए safe हैं।


🧠 9. Global Exception Handler (Most Important Section)

Large servers में हर try–catch लिखना impractical है।
इसलिए एक global exception handler सेट किया जाता है:

With ASP.NET Core:

app.UseExceptionHandler("/error");

या custom middleware:

app.Use(async (ctx, next) => { try { await next(); } catch(Exception ex) { File.AppendAllText("global_errors.log", ex.ToString()); ctx.Response.StatusCode = 500; } });

अब कोई भी error → server crash नहीं करेगा।


🧱 10. GPS TCP Server में Global Try–Catch (Must-have)

Main thread:

try { while(true) AcceptConnections(); } catch(Exception ex) { LogFatal(ex); }

Processing thread:

try { ProcessAllPackets(); } catch(Exception ex) { LogFatal(ex); }

इससे पूरा server कभी crash नहीं होगा।


📌 11. Error Logging — Very Important

void LogError(Exception ex) { File.AppendAllText("Errors/error.txt", $"{DateTime.Now} | {ex.Message} | {ex.StackTrace}\n"); }

GPS servers में tracing बहुत आसान हो जाती है।


🛡 12. Retry Logic (Advanced)

DB slow हो:

for(int i=0;i<3;i++) { try { await _db.SaveAsync(device); break; } catch { await Task.Delay(200); } }

अब server stable रहेगा।


⚠ Common Mistakes (Avoid These)**

❌ Empty catch

catch {}

सबसे dangerous mistake → error कभी पता ही नहीं लगेगा।

❌ Catch में throw new Exception()
Old stack info lost हो जाती है।

❌ Log न करना
Debugging impossible।

❌ हर जगह try–catch
Performance degrade।

✔ Use global handler instead.


🔚 Conclusion

C# Exception Handling आपके server को बनाता है:

✔ Crash-proof
✔ Stable
✔ Secure
✔ Debuggable
✔ Production-ready
✔ Enterprise-safe

GPS server में exception handling ही
server को 24×7 बिना रुके चलने देता है।

Post a Comment

0 Comments

Translate

Close Menu