What is Error Handling?
Error handling is the process of anticipating, detecting, and responding to runtime anomalies in software. Proper handling improves reliability, usability, and maintainability.
General Best Practices
- Prefer exceptions over error codes where the language supports them.
- Never swallow errors silently; log them with context.
- Provide user-friendly messages without exposing internal details.
- Use specific exception types to differentiate error conditions.
- Clean up resources (files, connections) in finally blocks or using scoped constructs.
JavaScript
Use try...catch
for synchronous code and .catch()
or async/await
for promises.
// Synchronous example
function parseJSON(str) {
try {
return JSON.parse(str);
} catch (e) {
console.error('Invalid JSON:', e);
return null;
}
}
// Asynchronous example
async function fetchData(url) {
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
console.error('Fetch error:', err);
throw err; // rethrow for callers
}
}
Python
Use try...except
blocks and the finally
clause for cleanup.
def read_file(path):
try:
with open(path, 'r') as f:
return f.read()
except FileNotFoundError as e:
print(f"File not found: {e}")
return None
except Exception as e:
print(f"Unexpected error: {e}")
raise
Java
Use try...catch
with specific exception types and try-with-resources
for automatic resource management.
public String readFile(String path) {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.lines().collect(Collectors.joining("\n"));
} catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
return null;
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
throw new RuntimeException(e);
}
}