All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.delphi.rules.community-delphi.CatchingRawException.html Maven / Gradle / Ivy

The newest version!

Why is this an issue?

The purpose of catch blocks is to recover from what went wrong in the try block. If it's not known which error occurred, then it is difficult to know how to recover.

This can lead to overly general error handling scenarios, like blindly displaying a "something went wrong" message.

Catching all exceptions regardless of whether they are expected to be raised or not may also hide bugs. For example, a new bug raising an unexpected exception might introduced within the try block. A more specific catch block would not swallow this exception.

Code that catches specific exceptions is also much clearer, aiding the long-term maintainability of your code.

How to fix it

Rewrite the exception handling block to catch specific exception types:

try
  Contents := TFile.ReadAllText(FileName, TEncoding.UTF8);
except
  on E: Exception do begin
    Writeln('Could not read file');
  end;
end;
try
  Contents := TFile.ReadAllText(FileName, TEncoding.UTF8);
except
  on E: EFileNotFoundException do begin
    Writeln('The file you have specified does not exist');
  end;
  on E: EEncodingError do begin
    Writeln('The file you have specified is not UTF-8 encoded');
  end;
end;




© 2015 - 2024 Weber Informatics LLC | Privacy Policy