Errors may occur during the execution of the program.
Some mistakes are difficult to foresee. For example, a file may not be readable.
When an error occurs, an exception appears.
An exception is an object that describes an erroneous situation.
In the try block, write the code in which there may be an error.
If an error occurs, the catch block will be executed.
Java
try
{
// Code that may fail
}
catch (Exception e)
{
}
Java
Creating a new Java console application ... and write the code
public class Main {
public static void main(String[] args) {
try {
float result = CalculateDensity(7, 0); // There will be a division by zero error here
System.out.println("Mass = " + result);
}
catch (Exception e)
{
}
}
public static float CalculateDensity(float mass, float volume)
{
return mass/volume;
}
}