Java throw exception in function

Java throw exception in function

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

How to Throw Exceptions

Before you can catch an exception, some code somewhere must throw one. Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java runtime environment. Regardless of what throws the exception, it’s always thrown with the throw statement.

As you have probably noticed, the Java platform provides numerous exception classes. All the classes are descendants of the Throwable class, and all allow programs to differentiate among the various types of exceptions that can occur during the execution of a program.

You can also create your own exception classes to represent problems that can occur within the classes you write. In fact, if you are a package developer, you might have to create your own set of exception classes to allow users to differentiate an error that can occur in your package from errors that occur in the Java platform or other packages.

You can also create chained exceptions. For more information, see the Chained Exceptions section.

The throw Statement

All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class. Here’s an example of a throw statement.

throw someThrowableObject;

Let’s look at the throw statement in context. The following pop method is taken from a class that implements a common stack object. The method removes the top element from the stack and returns the object.

public Object pop() < Object obj; if (size == 0) < throw new EmptyStackException(); > obj = objectAt(size - 1); setObjectAt(size - 1, null); size--; return obj; >

The pop method checks to see whether any elements are on the stack. If the stack is empty (its size is equal to 0 ), pop instantiates a new EmptyStackException object (a member of java.util ) and throws it. The Creating Exception Classes section in this chapter explains how to create your own exception classes. For now, all you need to remember is that you can throw only objects that inherit from the java.lang.Throwable class.

Читайте также:  Python stream file line by line

Note that the declaration of the pop method does not contain a throws clause. EmptyStackException is not a checked exception, so pop is not required to state that it might occur.

Throwable Class and Its Subclasses

The objects that inherit from the Throwable class include direct descendants (objects that inherit directly from the Throwable class) and indirect descendants (objects that inherit from children or grandchildren of the Throwable class). The figure below illustrates the class hierarchy of the Throwable class and its most significant subclasses. As you can see, Throwable has two direct descendants: Error and Exception .

Error Class

When a dynamic linking failure or other hard failure in the Java virtual machine occurs, the virtual machine throws an Error . Simple programs typically do not catch or throw Error s.

Exception Class

Most programs throw and catch objects that derive from the Exception class. An Exception indicates that a problem occurred, but it is not a serious system problem. Most programs you write will throw and catch Exception s as opposed to Error s.

The Java platform defines the many descendants of the Exception class. These descendants indicate various types of exceptions that can occur. For example, IllegalAccessException signals that a particular method could not be found, and NegativeArraySizeException indicates that a program attempted to create an array with a negative size.

One Exception subclass, RuntimeException , is reserved for exceptions that indicate incorrect use of an API. An example of a runtime exception is NullPointerException , which occurs when a method tries to access a member of an object through a null reference. The section Unchecked Exceptions — The Controversy discusses why most applications shouldn’t throw runtime exceptions or subclass RuntimeException .

Источник

Throwing Exceptions in Java

How to Throw Exceptions in Java

How to Throw Exceptions in Java

It is important to understand how to throw exceptions in Java. This will allow you to create higher quality code where errors are checked at compile time instead of runtime, and create custom exceptions that make debugging and recovery easier.

How to throw exceptions in Java

Throwing an exception is as simple as using the «throw» statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc. Here is an example that shows how to throw an exception:

throw new Exception("Exception message");

It’s limiting to use a generic exception because it makes it difficult for the calling code to catch it. It’s better to throw custom exceptions, which we will come back to in a bit.

Читайте также:  Php parse html data

Using the Throws keyword

Throws is a keyword used to indicate that this method could throw this type of exception. The caller has to handle the exception using a try-catch block or propagate the exception. We can throw either checked or unchecked exceptions.

The throws keyword allows the compiler to help you write code that handles this type of error, but it does not prevent the abnormal termination of the program. With the help of the throws keyword, we can provide information to the caller of the method about the types of exceptions the method might throw.

type method_name(parameters) throws exception_list

In the above syntax, exception_list is a comma-separated list of all the exceptions a method might throw. For example:

void testMethod() throws ArithmeticException, ArrayIndexOutOfBoundsException < // rest of code >

In the example below, we have created a test method to demonstrate throwing an exception. The toString() method returns a textual representation of an object, but in this case the variable is null. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException .

static void testMethod() throws Exception

This must be handled with a try/catch block:

public class Example < public static void main(String[] arg) < try < testMethod(); >catch (Exception e) < e.printStackTrace(); >> >

The Exception class

To use exceptions within your application more effectively, it is important to understand how to create and throw your own. But before we get into throwing exceptions, let’s first take under the hood: We’ll describe what an exception is and how to define your own, starting with the global exception class that all Java exceptions stem from:

package java.lang; public class Exception extends Throwable < static final long serialVersionUID = -3387516993124229948L; public Exception() < super(); >public Exception(String message) < super(message); >public Exception(String message, Throwable cause) < super(message, cause); >public Exception(Throwable cause) < super(cause); >protected Exception(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) < super(message, cause, enableSuppression, writableStackTrace); >>

The Exception class is the superclass of all classes that represent recoverable exceptions. When exceptions are thrown, they may be caught by the application code. The exception class extends Throwable . The constructor contains two parameters: message and cause. The detailMessage parameter gives the details of the message for this exception, and the throwable parameter gives the cause of this exception.

Types of exceptions

There are two types of exceptions in Java: checked (compile time) exceptions and unchecked (runtime) exceptions. For clarity, we’ll also discuss how errors are different than exceptions in Java.

Checked exception (compile time exception)

Checked exceptions must be caught and handled during compile time. If the compiler does not see a try or catch block or throws keyword to handle a checked exception, it throws a compilation error. Checked exceptions are generally caused by faults outside code like missing files, invalid class names, and networking errors.

FileInputStream fis = null; try < fis = new FileInputStream("B:/myfile.txt"); >catch (FileNotFoundException e)

Unchecked exception (runtime exception)

Unchecked exceptions do not need to be explicitly handled; they occur at the time of execution, also known as run time. These exceptions can usually be avoided by good coding practices. They are typically caused by programming bugs, such as logic errors or improper use of APIs. These exceptions are ignored at the time of compilation. For example:

Читайте также:  Python selenium webdriver linux

The example above will cause an ArithmeticException at the time of program, since a number can’t be divided by 0. It would throw an unhandled exception and the program would end.

Errors

People often refer to «errors» and “exceptions” as the same thing colloquially. However, in Java these are separate concepts. Errors are thrown by the Java Virtual Machine and cannot be caught or handled. They derive from java.lang.Error and they occur because of some fault in the environment in which the application is running. For example, stack overflows and out of memory exceptions are environment errors that result in the application exiting.

Custom exceptions

Java’s built-in exceptions don’t always provide the information we need. So, we sometimes need to supplement these exceptions with our own. During some specific operation, if an exception occurs in your application, you need to recover and make the user know about it. A custom exception gives you more control to provide extra data about the problem and to handle the exception in your code.

The best practice is to extend the java.lang.Exception class with a new class, following the general naming convention as provided by the JDK (Java Development Kit). The new class requires a constructor that will take a string as the error message—it is called the parent class constructor.

public class HandledException extends Exception < private String code; public HandledException(String code, String message) < super(message); this.setCode(code); >public HandledException(String code, String message, Throwable cause) < super(message, cause); this.setCode(code); >public String getCode() < return code; >public void setCode(String code) < this.code = code; >>

For example, let’s say a program fails to connect to a database. You could use a custom exception to collect information like the database URL, username, password, etc. In the catch block, you could write this information to the log and display a basic message to the user like «failed to connect to database.»

public class MainClass < private static String DATABASE_EXCEPTION = "DATABASE_EXCEPTION"; private static final Logger logger = Logger.getLogger(MainClass.class); public static void main(String[] args) < try < makeDatabaseConnection(); >catch (HandledException e) < rollbar.error(e, "Hello, Rollbar"); // Display custom message to the user System.out.println("Code: "+e.getCode()+” Exception Message : ”+e.getMessage()); // Log the exception detail logger.error("Exception: ", e); >> static void makeDatabaseConnection() throws HandledException < String dbURL = "jdbc:sqlserver://localhost\sqlexpress"; String userName = "sa"; String password = "secret"; Connection conn = null; try < conn = DriverManager.getConnection(dbURL, userName, password); >catch (SQLException e) < rollbar.error(e, "Hello, Rollbar"); throw new HandledException(DATABASE_EXCEPTION,"Failed to connect to database", e); >> >

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Rollbar can help throw Java exceptions as well as track, analyze, and manage errors in real-time to help you to proceed with more confidence. Try it today!

Источник

Оцените статью