In: Computer Science
How can I write a Python program that runs without crashing even though it has an error that a compiler would have caught and how can I write a Java program that crashes even after the compiler checked it. Please add comments that explain the problem, the outcome, and what this proves in both of the programs.
Python Program:
tempList= ['a', 0, 2]
for values in tempList:
try:
print("The value is", values)
r = 1/int(values)
break
except:
print("Oops!", sys.exc_info()[0], "occurred.")
print("Next value.")
print()
print("The reciprocal of", values, "is", r)
This Program runs a loop through the list , and prints the value of the reciprocal , if the element is an integer , otherwise it throws an exception. The portion that can cause an exception is placed inside the try block.The code that handles the exceptions is written in the except clause. This exception is produced by the compiler itself , in this case the exception is seen when the element is 'a' , which is a character and a reciprocal of a character variable is not possible , as there is a type mismatch. Also for the value 0 , anything divided by 0 is undefined , hence an error is thrown by compiler again.
Output:
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.
The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.
The entry is 2
The reciprocal of 2 is 0.5
Java Program:
int tempList[]={1,2,3};
for(int i=0;i<3;i++)
{
if(tempList[i]==2)
throw new ArithmeticException("Value is not valid");
else{
double r=1/tempList[i];
System.out.println("Reciprocal is "+r);
}
}
Output:
Reciprocal is 1.0
Exception in thread main java.lang.ArithmeticException:Value is not valid
Reciprocal is 0.33
This Program runs a loop through the list , and prints the value of the reciprocal , if the element is anything other than 2 , if the value is 2 it throws an Arithmetic Exception. Though the compiler does not throw an error, we throw an error explicitly , by using the keyword throw, followed by the instance exception you want to throw.
This shows that we can do exception handling in Python and throw a custom exception when needed in Java. This is basically a property of an OOP based programming language , and vice versa is also applicable.