It has the features described in this article and a few more examples of error handling scenarios. Responsible in fixing the production issues which are tagged to Releases. document.getElementById( "ak_js_1" ).setAttribute( "value", ( new Date() ).getTime() ); This site uses Akismet to reduce spam. methods support a variety of return types such as ResponseEntity, String, or even void. Launching the CI/CD and R Collectives and community editing features for How do you assert that a certain exception is thrown in JUnit tests? Error codes can be used by clients in their code to drive But what if want to manipulate the structure of the response payload as well? Basically, this class extends the ResponseEntityExceptionHandler class provided by Spring. Summary. POST : Should create new resource. Is there a colloquial word/expression for a push that helps you to start to do something? Lastly, we also want to handle validation errors in the response. Exception Handler The @ExceptionHandler is an annotation used to handle the specific exceptions and sending the custom responses to the client. Save my name, email, and website in this browser for the next time I comment. Lets learn how to handle exceptions in Spring Boot properly and wrap them into a better JSON representation to make life easier for our API clients. How to Run Your First Spring Boot Application in Spring Tool Suite? as they are raised because of syntactically invalid input, but we should always log unknown exceptions in the catch-all handler. In this post, I will show you how we can handle exceptions using Spring's aspect-oriented programming. with this functionality. Say if you want to shutdown your connection pool and reconnect after X minutes then you can try using the after throwing AOP approach - keep in mind that you will have to ensure thread safety while shutting down and restarting. In this article, we saw how Spring Boot translates those exceptions into a user-friendly output for our Using Spring Boot @ExceptionHandler Annotation: @ExceptionHandler annotation provided by Spring Boot can be used to handle exceptions in particular Handler classes or Handler methods. Default error response provided by Spring Boot contains all the details that are typically needed. Unfortunately, this is as far as we can go with the server.error configuration properties, so well have to look at the annotations that Spring Boot offers. 500 - SERVER ERROR is possible with all the above HTTP methods. Actually, the error is with the request. In SpringMVC the request is handled by Controller classes method if any error occurred in any particular method of the controller class then it can be handled in that @Controller class only -this is the local exception handling. In the catch block, the ResponseEntity object is used to send a custom error message with a status code as a response. In this spring boot example, we will see primarily two major validation cases -. field is empty, which we might want to contain something like Item with id 1 not found. You should handle such scenarios gracefully in the application. A cause. Exception Handling in Spring Boot REST API, JWT Token Authentication in Spring Boot Microservices, Hikari Configuration for MySQL in Spring Boot 2, Reading External Configuration Properties in Spring, Caching in Spring RESTful Service: Part 2 Cache Eviction, Caching in Spring Boot RESTful Service: Part 1, Implementing HTTP Basic Authentication in a Spring Boot REST API, Consul Miniseries: Spring Boot Application and Consul Integration Part 3, Consul Miniseries: Spring Boot Application and Consul Integration Part 2, Consul Miniseries: Spring Boot Application and Consul Integration Part 1, Why You Should be Using Spring Boot Docker Layers, Stay at Home, Learn from Home with 6 Free Online Courses. Just adding the dependencies and doing the configuration details is enough to create a DataSource and connect the Database. To do so,extend BasicErrorController, add a public method with a @RequestMapping that has a, produces attribute, and create a bean of your new type. Well identify the challenges we face while doing that, and then we will try to overcome those using these annotations. For that, we have to create a class implementing ErrorController as follows. A couple of things are new which we will talk about in a while. Here, we are using the ErrorModel class we just declared. newsletter. The ability to handle errors correctly in APIs while providing meaningful error messages is a desirable feature, as it can help the API client respond to issues. It contains all the details that are typically needed. By clicking Post Your Answer, you agree to our terms of service, privacy policy and cookie policy. handleAllUncaughtException() method will finally handle the exception. Almost done! The exception field is only valuable to Java developers, and the message leaves the API consumer lost in implementation details that are irrelevant to them. A typical scenario is an HTTP code 400: BAD_REQUEST when the client, for example, sends an improperly formatted field, like an invalid email address. eg. The product record was written into the database, and the order record was rolled back. This annotation, if used on methods of controller classes, will serve as the entry point for handling exceptions thrown within this controller only. simply need to create a method either in the controller itself or in a @ControllerAdvice class and Since we are on the mission to shape our own error response, we dont want that. You can also define a class annotated with @ControllerAdvice to customize the JSON document return for a particular controller and/or exception type, as shown in the following example: Earlier we saw how to use ErrorController to map all the unhandled error of your application so that instead of the default while label error page you can redirect the error to a method which will send a more sensible response. Lets quickly look at the default Exception Handling features provided by Spring Boot. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. So, I would rather return a 404 - Resource not found. some business logic based on it. (PROP_UNKNOWN_PROPERTY) 2. in the return value for the first function ResponseEntity is a raw type. Spring Boot provides some properties with which we can add the exception message, exception class, or even a stack trace Suspicious referee report, are "suggested citations" from a paper mill? Handle Database Connection Errors in Spring Boot during startup and after startup, The open-source game engine youve been waiting for: Godot (Ep. With this annotation, we can define how to treat such an exception in a single place, and the system will call this handler for thrown exceptions on classes covered by this ControllerAdvice. You can specify the Response Status for a specific exception along with the definition of the Exception with @ResponseStatus annotation. Spring Security : check whether you have multiple ContextLoader* definitions in your web.xml! @ExceptionHandler(value={IOException.class}) public ResponseEntity<String> handleIOException() {. So we need to have a common place where we can manage and handle all kinds of exceptions and send the respective error code for the API response depending on the exception types. Its good to have a single repository of We don't need to catch any exception at each method or class separately instead you can just throw the exception from the method and then it will be caught under the central exception handler class annotated by @ControllerAdvide. A-143, 9th Floor, Sovereign Corporate Tower, We use cookies to ensure you have the best browsing experience on our website. Thats a cool error response. Certainly, we will not want our end-users to see a long error stack trace of null pointer exception or any database exception which is just meaningless and annoying to a very laymen users. any idea why this happen? 542), We've added a "Necessary cookies only" option to the cookie consent popup. This is the response when you try getting details of a non existing student http://localhost:8080/students/9. In this post, I will explain how to gracefully handle exceptions in Spring Boot RESTful services. in the application and not just ProductController. In fact, the proper approach is to return a HTTP code 404 (NOT FOUND) as specified in the HTTP/1.1 spec. As we all know, exception handling is the most important and a crucial thing in Spring Boot Rest APIs, which helps us to perform conditional and unconditional checkings for our code and handle any kind of exception in a proper way. The code for the BlogNotFoundException class is this. Should be idempotent (same result in multiple calls). So lets create a custom ErrorResponse class so that the exception is conveyed to the user in a clear and concise way as follows: The addCustomer() method defined by CustomerController throws a CustomerAlreadyExistsException when the user tries to add a Customer that already exists in the database else it saves the customer details. We can have multiple exception handlers to handle each exception. Let's go through the steps. We will look at few methods outlining how to do a better error handling for REST API using Spring Boot. Spring Boot provides a web tool called Spring Initializer to bootstrap an application quickly. ExceptionHandler is a Spring annotation that provides a mechanism to treat exceptions thrown during execution of handlers (controller operations). What are the default exception handling capabilities provided by Spring Boot? Jordan's line about intimate parties in The Great Gatsby? Which Langlands functoriality conjecture implies the original Ramanujan conjecture? Can a private person deceive a defendant to obtain evidence? Retracting Acceptance Offer to Graduate School. Tell the user what was wrong in the input. What are the consequences of overstaying in the Schengen area by 2 hours? How to create a project using Spring Boot, MyBatis and MySQL? eg. and Goodreads. The annotated class will act like an Interceptor in case of any exceptions. Spring provides a very elegant solution to this problem in form of controller advice. In this article, we will see how to use Java 8 Optional In Real-time Projects Let's take an example of Creating CRUD Operations using Spring and Hibernate Framework. Another solution is to use AOP, but I am not the expert; someone else could probably elaborate more. custom errors code likes. understand in brief how Spring handles it and when one mechanism gets prioritized over the other. How to connect ReactJS as a front-end with PHP as a back-end ? The code to handle BlogNotFoundException in the getBlogById() method is this. What is the ideal amount of fat and carbs one should ingest for building muscle? Avoiding bottleneck DAO code using Spring data JPA. Processing JSON Data in Spring Boot. For that we need to use @ExceptionHandler annotation in that particular controller class for which we want to handle our exception. Check 'errors' field for details. Here are some additional resources that helped in the composition of this article: A uniform error format allows an API client to parse error objects. The first approach is to use Java try-catch block to handle the exception in the controller methods. If our service calls this method and returns directly to the controller, well get an HTTP code 200 (OK) even if the resource isnt found. Keeping these points in mind we will go with the following payload for the error response: Now, lets apply all these to our NoSuchElementFoundException handler method. Enter your Username and Password and click on Log In Step 3. @ExceptionHandler This annotation can be used to handle the exception at the controller level. Exception and error messages sent to clients should be short and meaningful. Now lets go through the various ways in which we can handle the Exceptions thrown in this project. thanks for a great tutorial! Connect and share knowledge within a single location that is structured and easy to search. Find centralized, trusted content and collaborate around the technologies you use most. in our Spring-defined error response payload. Particularly, Spring Boot looks for a mapping for the / error endpoint during the start-up. Note: Spring Boot allows to annotate a method with @ResponseStatus to return the required Http Status Code. @ControllerAdvice(basePackages = "org.example.controllers") - This will only scan call the mentioned package and handle the exceptions for the same. Well use the source code hosted on GitHub as an example application that implements a REST API for retrieving objects that represent birds. Building REST APIs with Spring became the standard approach for Java developers. Learn how your comment data is processed. For transaction management, the Spring Framework offers a stable abstraction. "You can't just keep it simple. If it fails to find it then it will look for a handler of the parent exception, which in our case is RuntimeException, and if none is found, the We can definitely implement our own controller that will override this default behavior. References to generic type ResponseEntity should be parameterizedJava(16777788). This method returns a ResponseEntity that wraps a custom error message and a status code. To achieve this, we have first introduced a server-side configuration property named reflectoring.trace which, if set to true, To redirect the exception to our advice we need to set a couple of properties in the the properties file: spring.mvc.throw-exception-if-no-handler-found=true and spring.web.resources.add-mappings=false Credit: Stackoverflow user mengchengfeng. Create and use data class for the exception: Instead of using the built-in exception classes, . To actually get a stackTrace in an API response, our clients must additionally pass the For that, we have to create a class implementing, But what if we have multiple controller class throwing the same type of exception, say IOException? A more complex error could implement the ApiSubError class and provide more details about the problem so the client can know which actions to take. The subset of controllers affected can be defined by using the following selectors on @ControllerAdvice: annotations(), basePackageClasses(), and basePackages(). So in REST API development, it carries a bigger role. The default behavior returns stack traces that are hard to understand and ultimately useless for the API client. The response is shown in this Figure. Lets enhance the GET method to throw this exception when a student is not found. I am also "open for hire", Your donation will help us to improve our content, site maintenance, and community improvement. Do we need to write a separate, This is particularly useful if you want to add a handler for a new content type (the default. How/What to think when you design error handling for REST API? Editors note: This article was updated on September 5, 2022, by our editorial team. identical to the code we saw in the @ExceptionHandler section. This site uses cookies to track analytics. The term 'Advice' comes from Aspect-Oriented Programming (AOP) which allows us to inject cross-cutting code (called "advice") around existing methods. Below, youll see examples of JSON responses generated after implementing these improvements. more than 150 reviews on Amazon By using @ExceptionHandler and @ControllerAdvice, well be able to define a central point for treating exceptions and wrapping them in an ApiError object with better organization than is possible with the default Spring Boot error-handling mechanism. Following screen shot shows the structure of the project we will create. Validating user inputs is not a difficult task, but it is rather cumbersome. As you can see we have overridden two of the ResponseEntityExceptionHandler methods: This exception occurs when you try to call an API that doesn't exist in the system. So, what should you when an error or exception happens in a RESTful service? In our case we throw RunTimeException and StudentNotFoundException - so we have 2 exception handlers. Spring provides the @ExceptionHandlerannotation to handle exceptions in specific handler classes or handler methods. Also, the annotation @ResponseStatus(HttpStatus.NOT_FOUND) on the handler method is not required as the HTTP status passed into the ResponseEnity Gets information about a bird and throws an exception if not found. Such classes enable us to customize an exception according to the callers needs. that allow us to treat exception handling as a cross-cutting concern: Before jumping into these annotations we will first look at how Spring handles exceptions thrown by our web controllers - our last line of defense for catching an exception. Making statements based on opinion; back them up with references or personal experience. It provides Step 2: Creating a CustomerRepository Interface. In that case, you can define a specific error response structure. on how to fix them or a link to API docs. The status and error message - 500 - indicates that something is wrong with our server code but actually its a client error because the client provided an invalid id. Handling exceptions is an important part of building a robust application. The main topics we are going to discuss here are, ", //Body omitted as it's similar to the method of same name, Get Your Hands Dirty on Clean Architecture, Spring Boots Default Exception Handling Mechanism, Getting started with Spring Security and Spring Boot, Demystifying Transactions and Exceptions with Spring, An error code that tells the client what kind of error it is. So if we have multiple methods throwing the same type of exception then all those requests will be handled by this same @ExcptionHandler method. If a method call to getBlogById() throws BlogNotFoundException, the catch block handles the exception. Toptal handpicks top Java developers to suit yourneeds. I have many calls to jdbcTemplate across multiple DAO's, so putting a try/catch around each one is not the ideal answer. Altogether, the most common implementation is to use @ExceptionHandler on methods of @ControllerAdvice classes so that the Spring Boot exception handling will be applied globally or to a subset of controllers. 2. 1) annotations - Controllers that are annotated with the mentioned annotations will be assisted by the @ControllerAdvice annotated class and are eligible for exception of those classes. Along with its benefits, it also complicates the code and makes the code not easily readable to unknown users. I want the application to continue to operate normally regardless of being able to connect to the database. Spring Boot is built on the top of the spring and contains all the features of spring. In this example, we will see how can we handle a RuntimeException that will be thrown from CustomerController classes getCustomer() method. or an HTML web page. One is the code handles the exception using a try-catch block. How is "He who Remains" different from "Kang the Conqueror"? Do not include sensitive information in the response. If it is not already included in the build.gradle, add this line to the dependencies. How to Conduct a Two Sample T-Test in Python, Spring - Prepared Statement JDBC Template. Now what is the difference between local exception handling vs global exception handling? It's used to resolve standard Spring exceptions to their corresponding HTTP Status Codes, namely Client error 4xx and Server error 5xx status codes. The CustomerService interface defines three different methods: The Interface and service implementation class is as follows: Step 5: Creating Rest Controller CustomerController which defines various APIs. For example, the database may be down. Save $10 by joining the Simplify! In addition, it considerably reduces the amount of code written for exception handling. One thing I do not like is the status code of the response. Generate the project. The Customer class is annotated with @Entity annotation and defines getters, setters, and constructors for the fields. Establishing and deepening positive client. Here, the BlogRepository extends the CrudRepository of Spring Data JPA. If true the method throws a BlogAlreadyExistsException. Moving on! Your email address will not be published. Is lock-free synchronization always superior to synchronization using locks? I like to write blogs and contribute the code in the opensource git repository which helps other developers to do things easily and fast. This is one of the ways we can generate a global response for all of the unhandled Exception. This annotation makes our life easy to handle all kinds of exceptions at a central place in our application. Lets see how can we extend handleHttpMessageNotReadable() to handle HttpMessageNotReadableException exceptions. @ControllerAdvice constructor comes with some special arguments, which allows you to scan only the related portion of your application and handle only those exceptions thrown by the respective classes mentioned in the constructor. Hey Customer, We are busy, please come back later. Choose the right HttpStatus code for differents situations in your RestControllerAdvice : Parameters null or value not set : 400 => Bad request Returned value not found (record or list empty) : 404 => Not found Exception from server (database error, network error etc.) So in this tutorial, I'm going to explain how we can configure exception handling in spring boot REST API. So we like to request that if you can donate a small amount then will be more valuable to us. Here is what the response for the GET /birds/2 endpoint looks like now: It is important to control exception handling so we can properly map exceptions to the ApiError object and inform API clients appropriately. Well provide the exception EntityNotFoundException as a parameter for this handleEntityNotFound method: Great! as part of the response payload: Using these Spring Boot server properties in our application.yml we can alter the error response to some extent. Join the DZone community and get the full member experience. places: In this section, well be looking at the first case only. What tool to use for the online analogue of "writing lecture notes on a blackboard"? data.sql - Initial data for the student table. I want to catch those connection exceptions and handle them differently. One thing I would like to note here is that even if we dont have this catch-all exception handler, Spring will handle it Then where does this white label error come from? Can patents be featured/explained in a youtube video i.e. It gives better readability. Should I Use Spring REST Docs or OpenAPI? The code for the Blog Entity class is this. Our current status code doesnt correctly reflect that. [StructLayout (LayoutKind. Exception handling is one of the most important features of any software application, either a monolithic web or REST full API or microservice. A combination of Spring and Spring Boot provide multiple options to customize responses for errors. Go to Azure Active Directory Guest Access website using the links below Step 2. For example, to map 404 to a static HTML file, your folder structure would be as follows: Your email address will not be published. For instance, by properly handling exceptions, you can stop the disruption of the normal flow of the application. When annotating a method with @ExceptionHandler, a wide range of auto-injected parameters like WebRequest, Locale, and others may be specified as described here. Class extends the ResponseEntityExceptionHandler class provided by Spring custom responses to the cookie consent popup well... To search CI/CD and R Collectives and community editing features for how do you assert a... Responses for errors HTTP methods overcome those using these annotations will explain how to gracefully exceptions. Could probably elaborate more Customer class is annotated with how to handle database exceptions in spring boot Entity annotation and defines getters setters. To request that if you can specify the response status for a mapping for the using. With all the details that are typically needed already included in the opensource git repository helps... Even void the Conqueror '' all kinds of exceptions at a central place in our application syntactically input... Responsestatus annotation with its benefits, it considerably reduces the amount of fat and carbs one should ingest building. My name, email, and website in this post, I explain... We also want to handle the exception: Instead of using the exception. Customer, we use cookies to ensure you have multiple ContextLoader * definitions Your. Carries a bigger role Spring tool Suite called Spring Initializer to bootstrap an application quickly or void. Which we will try to overcome those using these annotations on log in Step.... Trusted content and collaborate around the technologies you use most can we handle RunTimeException. We have 2 exception handlers to handle the specific exceptions and sending the custom responses to the code we in. Exceptions at a central place in our application sent to clients should short! The client handle them differently field is empty, which we can generate a global response all... Method returns a ResponseEntity that wraps a custom error message and a code! Same result in multiple calls ) error messages sent to clients should parameterizedJava... To use @ ExceptionHandler section is a raw type handles it and when mechanism. Cases - and when one mechanism gets prioritized over the other what tool to use try-catch. Two major validation cases - the definition of the unhandled exception the at! Benefits, it considerably reduces the amount of fat and carbs one should ingest for building muscle Conduct a Sample! What is the status code as a front-end with PHP as a parameter for this handleEntityNotFound:. Errormodel class we just declared details is enough to create a project using Spring & # x27 ; aspect-oriented... Launching the CI/CD and R Collectives and community editing features for how you! Can specify the response because of syntactically invalid input, but I am not the expert ; someone could. The ideal amount of code written for exception handling vs global exception handling is one of the application handling! Else could probably elaborate more easily and fast with the definition of the exception task, we... An important part of building a robust application code not easily readable unknown! Tagged to Releases rather cumbersome an Interceptor in case of any exceptions an used. Boot provides a very elegant solution to this problem in form of controller advice either monolithic... { IOException.class } ) public ResponseEntity & lt ; String & gt ; handleIOException ( ) method GitHub... An application quickly it and when one mechanism gets prioritized over the other at! Rest APIs with Spring became the standard approach for Java developers at the exception! For transaction management, the Spring and Spring Boot is a Spring annotation that provides a very elegant to..., please come back later a combination of Spring and contains all details. Calls to jdbcTemplate across multiple DAO 's, so putting a try/catch around each one is the between. A specific exception along with its benefits, it also complicates the code the. Was updated on September 5, 2022, by our editorial team ( PROP_UNKNOWN_PROPERTY ) in! How we can handle exceptions using Spring Boot example, we are using the below! The Customer class is annotated with how to handle database exceptions in spring boot Entity annotation and defines getters, setters, and website this... Solution to this problem in form of controller advice handlealluncaughtexception ( ) throws BlogNotFoundException, the catch block, catch! The top of the exception mechanism gets prioritized over the other exceptions using Spring?. Method: Great for instance, by our editorial team handle BlogNotFoundException in the Schengen area 2! A youtube video i.e Creating a CustomerRepository Interface what was wrong in the Schengen area by 2 hours of able... Form of controller advice ) method will finally handle the exception with @ annotation. So, I will explain how to do things easily and fast busy, please come back later Entity is... An exception according to the database something like Item with id 1 found... `` writing lecture notes on a blackboard '' might want to handle exceptions. And website in this example, we are busy, please come back later easily fast... Form of how to handle database exceptions in spring boot advice certain exception is thrown in JUnit tests & # ;... Of the response a single location that is structured and easy to exceptions... Annotated with @ Entity annotation and defines getters, setters, and website in this,! In case of any software application, either a monolithic web or full! Approach for Java developers connect and share knowledge within a single location that is structured and easy to search through! In Step 3 lets enhance the GET method to throw this exception when a student is not the ;... Customerrepository Interface a specific exception along with the definition of the exception area by 2 hours try-catch. Saw in the catch block, the BlogRepository extends the CrudRepository of Spring to jdbcTemplate across multiple DAO 's so... The specific exceptions and handle them differently Customer, we use cookies to ensure you have multiple exception to... I want the application to continue to operate normally regardless of being able to connect to the,. Status for a push that helps you to start to do a better error handling for REST API development it. Blognotfoundexception in the application lecture notes on a blackboard '' defines getters,,. Quickly look at the default exception handling capabilities provided by Spring Boot is a microservice-based framework making! What should you when an error or exception happens in a while have! Response provided by Spring Boot basically, this class extends the CrudRepository of Spring data JPA method with @ to! Case we throw RunTimeException and StudentNotFoundException - so we like to write blogs and contribute the code for the error... Code handles the exception the consequences of overstaying in the @ ExceptionHandler is an important part of a... Run Your first Spring Boot RESTful services show you how we can have multiple exception to. Talk about in a while RESTful services specific exceptions and sending the custom to... This handleEntityNotFound method: Great properly handling exceptions, you can define a specific error response provided by Spring allows... Handle a RunTimeException that will be thrown from CustomerController classes getCustomer ( ) { RESTful service cookie. We extend handleHttpMessageNotReadable ( ) method find centralized, trusted content and around. And connect the database the above HTTP methods code we saw in catch. The user what was wrong in the catch block handles the exception can generate a global response all! In which we will try to overcome those using these annotations, should. Can have multiple ContextLoader * definitions in Your web.xml stack traces that are typically.! For retrieving objects that represent birds be parameterizedJava ( 16777788 ) - Prepared Statement JDBC Template those using these.! Of things are new which we will talk about in a RESTful service create and use data class which. Is thrown in this Spring Boot allows to annotate a method call to getBlogById ( ) method will handle. So putting a try/catch around each one is the ideal amount of code written for exception handling that a exception! But we should always log unknown exceptions in Spring tool Suite we use to. On opinion ; back them up with references or personal experience was rolled back to write blogs and contribute code! Can patents be featured/explained in a RESTful service one should ingest for building muscle ErrorModel class we just.! And making a production-ready application in it takes very little time first is... Contribute the code for the online analogue of `` writing lecture notes on a blackboard?! Production issues which are tagged to Releases gracefully handle exceptions using Spring Boot application in Spring Boot is a annotation! Into the database I comment let & # x27 ; s go through the steps method this! 2022, by properly handling exceptions, you agree to our terms of service, privacy policy and cookie.... Exceptions at a central place in our case we throw RunTimeException and StudentNotFoundException - so we have to a... Someone else could probably elaborate more the dependencies and doing how to handle database exceptions in spring boot configuration is... Can define a specific exception along with the definition of the application to continue to operate normally regardless being. Is a Spring annotation that provides a mechanism to treat exceptions thrown during of... The status code terms of service, privacy policy and cookie policy specify the.! Conduct a two Sample T-Test in Python, Spring - Prepared Statement JDBC Template Your,! Blogrepository extends the CrudRepository of Spring and Spring Boot particular controller class for which might... Get the full member experience useless for the API client to continue to operate normally regardless of able... Now what is the status code hey Customer, we will look at methods... Controller methods which Langlands functoriality conjecture implies the original Ramanujan conjecture, setters, website. And makes the code and makes the code to handle the exception using a try-catch....