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 {
}
✅ Valid – try can have only finally.
try {
} catch(Exception e) {
}
✅ Valid
try {
} catch(Exception e) {
} finally {
}
✅ Valid
try {
} catch(ArithmeticException e) {
} catch(Exception e) {
}
✅ Valid
Child exception first, then parent.
try {
} catch(Exception e) {
} catch(ArithmeticException e) {
}
❌ Syntax Error
Parent exception (Exception) comes before child (ArithmeticException).
Child catch becomes unreachable.
try {
} finally {
} catch(Exception e) {
}
❌ Syntax Error
catch cannot come after finally.
try {
} catch(ArithmeticException e) {
} finally {
} catch(Exception e) {
}
❌ Syntax Error
catch cannot appear after finally.
try {
} catch(Exception e) {
} finally {
} finally {
}
❌ Syntax Error
Only one finally block is allowed.
try {
}
❌ Syntax Error
try must have catch or finally.
catch(Exception e) {
}
❌ Syntax Error
catch cannot exist without try.
finally {
}
❌ Syntax Error
finally cannot exist without try.
try {
} catch(ArithmeticException e) {
} catch(ArithmeticException e) {
}
❌ Syntax Error
Duplicate catch block for the same exception.
try {
} catch(Exception e) {
} catch(RuntimeException e) {
}
❌ Syntax Error
RuntimeException is a child of Exception, so this catch is unreachable.
try {
} catch(RuntimeException e) {
} catch(Exception e) {
}
✅ Valid
Child exception first, then parent.
try {
} finally {
} finally {
}
❌ Syntax Error
Only one finally block allowed.
Top comments (0)