Alevel 2 Java 16APR AB
Alevel 2 Java 16APR AB
Syntax:
throw ThrowableInstance
Example:
class Throw1
{
static void validateMarks(int marks)
{
if (marks <80)
throw new ArithmeticException("Not Oracle certified");
else
System.out.println("Oracle certified ");
}
Explaination:
In this example, we have created the validateMarks () method that takes integer
value as a parameter. If the marks is less than 80, we are throwing the
ArithmeticException otherwise print a message that you are Oracle certified.
Java throws keyword:
Any method that is capable of causing exceptions must list all the exceptions
possible during its execution, so that programmer calling that method gets a prior
knowledge about which exceptions are to be handled. A method can do so by using
the throws keyword.
class Throws1
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
Explaination:
In this example the programmer makes a prior announcement that the code may be
risky so throws exception with the method itself.The above code will throw an
exception if the above mentioned file is not created first or gets deleted.
The difference between throw and throws
throw throws
Example: Example:
Exercise:
1. Why throw kewword is necessary?Explain with proper example.
2. Explain the usage of throws keyword with example.
3. Write down the differences between throw and throws keyword.