Creating your own exception

TharuniDiddekunta 417 views 2 slides Apr 04, 2019
Slide 1
Slide 1 of 2
Slide 1
1
Slide 2
2

About This Presentation

User defined exceptions (can create your own exceptions)


Slide Content

3/18/2019 Creating your own exception: Your Guided Course Template
https://canvas.instructure.com/courses/1480238/pages/creating-your-own-exception?module_item_id=21012890 1/2
Crea?ng your own excep?on
Types of Exception in Java
Built-in Exceptions
User-Defined Exceptions
Built-in exceptions:
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are suitable
to explain certain error situations.
User-Defined Exceptions
User Defined Exception or custom exception is creating your own exception class and throws that
exception using ‘throw’ keyword. This can be done by extending the class Exception.
Example of java custom exception:
class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
}
class TestCustomException1
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])

3/18/2019 Creating your own exception: Your Guided Course Template
https://canvas.instructure.com/courses/1480238/pages/creating-your-own-exception?module_item_id=21012890 2/2
{
try
{
validate(13);
}catch(Exception m)
{
System.out.println("Exception occured: "+m);
}
System.out.println("rest of the code...");
}
}

Output:Exception occured: InvalidAgeException:not valid
rest of the code...
Tags