Java |
try/catch statement
static int F(int a, int b) {
if (b == 0)
throw new Exception("Divide by zero");
return a / b;
}
public static void main(String[] args) {
try {
System.out.println(F(5, 0));
}catch(Exception e) {
System.out.println("Error");
}
}
nested try/finally statement
class Test
{
public static void main(String[] args) {
while (true) {
try {
try {
System.out.println("Before break");
break;
}
finally {
System.out.println("Innermost finally block");
}
}
finally {
System.out.println("Outermost finally block");
}
}
System.out.println("After break");
}
}
prints:
Before break
Innermost finally block
Outermost finally block
After break
throw statement
class Test
{
static void F() throws Exception {
try {
G();
}
catch (Exception e) {
System.out.println("Exception in F: " + e.getMessage());
e = new Exception("F");
throw e; // re-throw
}
}
static void G() throws Exception{
throw new Exception("G");
}
public static void main(String[] args) {
try {
F();
}
catch (Exception e) {
System.out.println("Exception in Main: " + e.getMessage());
}
}
}
>java Test
Exception in F: G
Exception in Main: F
|
|
C# |
try/catch statement
static int F(int a, int b) {
if (b == 0)
throw new Exception("Divide by zero");
return a / b;
}
static void Main() {
try {
Console.WriteLine(F(5, 0));
}catch(Exception e) {
Console.WriteLine("Error");
}
}
nested try/finally statement
class Test
{
static void Main() {
while (true) {
try {
try {
Console.WriteLine("Before break");
break;
}
finally {
Console.WriteLine("Innermost finally block");
}
}
finally {
Console.WriteLine("Outermost finally block");
}
}
Console.WriteLine("After break");
}
}
prints:
Before break
Innermost finally block
Outermost finally block
After break
throw statement
class Test
{
static void F() {
try {
G();
}
catch (Exception e) {
Console.WriteLine("Exception in F: " + e.Message);
e = new Exception("F");
throw; // re-throw
}
}
static void G() {
throw new Exception("G");
}
static void Main() {
try {
F();
}
catch (Exception e) {
Console.WriteLine("Exception in Main: " + e.Message);
}
}
}
>csc Test.cs
Exception in F: G
Exception in Main: F
|
|