DEV Community

Kesavarthini
Kesavarthini

Posted on

Exception Handling Tasks

Here we check whether each block is valid or syntax error according to Exception Handling rules.

Java Rules

  • try must be followed by at least one catch or finally.
  • catch blocks must come after try.
  • finally must be last.
  • Child exception must come before parent exception

try {
} finally {
}
Enter fullscreen mode Exit fullscreen mode

✅ Valid – try can have only finally.

try {
} catch(Exception e) {
}
Enter fullscreen mode Exit fullscreen mode

✅ Valid

try {
} catch(Exception e) {
} finally {
}
Enter fullscreen mode Exit fullscreen mode

✅ Valid

try {
} catch(ArithmeticException e) {
} catch(Exception e) {
}
Enter fullscreen mode Exit fullscreen mode

✅ Valid
Child exception first, then parent.

try {
} catch(Exception e) {
} catch(ArithmeticException e) {
}
Enter fullscreen mode Exit fullscreen mode

❌ Syntax Error
Parent exception (Exception) comes before child (ArithmeticException).
Child catch becomes unreachable.

try {
} finally {
} catch(Exception e) {
}
Enter fullscreen mode Exit fullscreen mode

❌ Syntax Error
catch cannot come after finally.

try {
} catch(ArithmeticException e) {
} finally {
} catch(Exception e) {
}
Enter fullscreen mode Exit fullscreen mode

❌ Syntax Error
catch cannot appear after finally.

try {
} catch(Exception e) {
} finally {
} finally {
}
Enter fullscreen mode Exit fullscreen mode

❌ Syntax Error
Only one finally block is allowed.

try {
}
Enter fullscreen mode Exit fullscreen mode

❌ Syntax Error
try must have catch or finally.

catch(Exception e) {
}
Enter fullscreen mode Exit fullscreen mode

❌ Syntax Error
catch cannot exist without try.

finally {
}
Enter fullscreen mode Exit fullscreen mode

❌ Syntax Error
finally cannot exist without try.

try {
} catch(ArithmeticException e) {
} catch(ArithmeticException e) {
}
Enter fullscreen mode Exit fullscreen mode

❌ Syntax Error
Duplicate catch block for the same exception.

try {
} catch(Exception e) {
} catch(RuntimeException e) {
}
Enter fullscreen mode Exit fullscreen mode

❌ Syntax Error
RuntimeException is a child of Exception, so this catch is unreachable.

try {
} catch(RuntimeException e) {
} catch(Exception e) {
}
Enter fullscreen mode Exit fullscreen mode

✅ Valid
Child exception first, then parent.

try {
} finally {
} finally {
}
Enter fullscreen mode Exit fullscreen mode

❌ Syntax Error
Only one finally block allowed.

Top comments (0)