0

I am using javac in Powershell right now, but I am having an issue. The message

selected file has been succesfully compiled:)

I made it show after compilation shows up even if there have been errors during compilation. Here is my current code:

function Compile {
javac (-join ($File, ".java"))
Write-Host $File -NoNewline -ForegroundColor Cyan
" has been succesfully compiled:)"}

I tried using the trap statement like this:

function Compile {
trap{
[System.Media.SystemSounds]::Exclamation.Play()
return}
javac (-join ($File, ".java"))
Write-Host $File -NoNewline -ForegroundColor Cyan
" has been succesfully compiled:)"}

and I also tried using try and catch

function Compile {
try {
javac (-join ($File, ".java"))}
catch{
[System.Media.SystemSounds]::Exclamation.Play()
return}
Write-Host $File -NoNewline -ForegroundColor Cyan
" has been succesfully compiled:)"}

but neither of those two actually worked. I need to find a way to sense javac errors. Is there a way to actually do that?

PlatoHero
  • 31
  • 5
  • In short: As of PowerShell 7.2.x, calls to external programs do _not_ cause PowerShell errors, which means that PowerShell's error-handling features (e.g. `try { ... } catch { ... }`) do not apply (except accidentally, due to a bug with `2>` redirections up to v7.1). Instead, check if `$LASTEXITCODE` is nonzero to determine whether an external program failed. _Future_ PowerShell versions may offer an _opt-in_ mechanism for integrating external-program calls into PowerShell's error handling. See [the linked duplicate](https://stackoverflow.com/a/67743340/45375) for details. – mklement0 Sep 18 '22 at 01:12

0 Answers0