Я получаю противоречивые сообщения об ошибках при попытке настроить блок try-catch-finally в методе класса, который возвращает строку.
Мой код:
class exampleClass {
[string]Create() {
try {
$rsa_Base64 = "string"
return $rsa_Base64
}
catch {
{...}
}
finally {
Remove-Item -Path $env:TEMP\test.txt
}
}
}
В этой ситуации я получаю сообщение об ошибке: Not all code path returns value within method.
Если я перенесу оператор return в блок finally, я получу ошибку: Flow of control cannot leave a Finally block.
Я хочу добавить блок finally, чтобы обеспечить удаление созданных файлов в операторе try.





Вы можете избежать этой проблемы, безоговорочно используя оператор return вне оператора try / catch/ finally:
class exampleClass {
[string]Create() {
$rsa_Base64 = '' # must initialize the variable
try {
$rsa_Base64 = "string"
}
catch {
{...}
}
finally {
Remove-Item -Path $env:TEMP\test.txt
}
return $rsa_Base64
}
}
Note the use of '' to initialize the variable; using $null would ultimately not be effective, because the method is [string]-typed, and PowerShell doesn't support $null in [string] values and converts them to '' (the empty string) - see this answer for more information.
Более правильно, однако, вы должны убедиться, что ваша ветка catch также содержит оператор управления потоком, выходящий из области действия [1], а именно return или throw (хотя технически exit тоже работает, его следует использовать только в файлах скриптов). , так как он выходит из сеанса в целом):
class exampleClass {
[string]Create() {
try {
$rsa_Base64 = "string"
return $rsa_Base64
}
catch {
{...}
return '' # must exit the method from this block too
}
finally {
Remove-Item -Path $env:TEMP\test.txt
}
}
}
[1] By contrast, the finally block not only doesn't need a scope-exiting statement, by design it doesn't support any. The reason is that this block is run outside the normal flow of control and is intended solely for cleanup.