Here is how you can throw and catch an exception in each of the languages you mentioned:
Java:
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
throw new IOException("An IOException occurred");
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
}
}
}
Python 3:
try:
raise IOError("An IOError occurred")
except IOError as e: print(f'Caught IOError: {e}')
C++:
#include <iostream>
#include <stdexcept>
int main() {
try {
throw std::runtime_error("A runtime error occurred");
} catch (const std::exception& e) {
std::cout << "Caught runtime error: " << e.what() << std::endl;
}
return 0;
}
JavaScript:
try {
throw new Error("An error occurred");
} catch (e) {
console.log(`Caught error: ${e.message}`);
}
I hope this helps! Let me know if you have any questions.
No comments:
Post a Comment